0

次の2つの機能があります。

import qualified Data.Text as T

noneOnEmptyA :: T.Text -> T.Text
noneOnEmptyA txt | T.null txt = "None."
                 | otherwise  = txt


noneOnEmptyB :: [T.Text] -> [T.Text]
noneOnEmptyB txts | null txts = ["None."]
                  | otherwise = txts

noneOnEmptyA1) 機能を達成し、2) 機能を達成するように持ち上げることができる単一の関数を作成することは可能noneOnEmptyBですか? 問題の核心は、空のリストをチェックしnoneOnEmptyAながら空のテキストをチェックすることです。noneOnEmptyBただし、noneOnEmptyAリストを操作するために持ち上げられた ( fmap noneOnEmptyAtype を返す場合のよう[T.Text]に) リスト自体が空であるかどうかをチェックするのではなく、リスト内の空のテキストをチェックします。

4

1 に答える 1

2

あなたができることの1つは、型クラスを導入することですNullable

{-# LANGUAGE OverloadedStrings #-}
module Stackoverflow where

import           Data.Text (Text)
import qualified Data.Text as T
import           Data.Monoid
import           Data.String

class Nullable a where
    isNull :: a -> Bool

instance Nullable Text where
    isNull = T.null

instance IsString a => IsString [a] where
    fromString str = [fromString str]

次に、関数を書くことができます

noneOnEmpty :: (Nullable a, IsString a, Monoid a) => a -> a
noneOnEmpty a | isNull a = "None" <> mempty
              | otherwise = a

アップデート

@DanielWagnerが指摘しているように - Monoid/ mempty/<>部分は必要ありません

noneOnEmpty :: (Nullable a, IsString a) => a -> a
noneOnEmpty a | isNull a = "None"
              | otherwise = a
于 2015-11-14T21:54:52.683 に答える