[英]haskell, case of like fmap
我有一个foo :: a -> a -> Either String TypeConstructor
类型的函数foo :: a -> a -> Either String TypeConstructor
foo
可以返回throwError String
和TypeConstructor
。
我想做一些类似fmap
事情。 我的意思是我想case (foo xyz) of ...
进行case (foo xyz) of ...
其中...
表示不同的值(取决于foo中使用的构造函数值)。
有没有办法做到这一点?
一种基本方法是对所有内容进行模式匹配
case foo x y of
Left string -> ...
Right (Cons1 z w) -> ...
Right (Cons2 a b c) -> ...
Right Cons3 -> ...
其中Cons1, ...
是Cons1, ...
的值构造TypeConstructor
。
你不能直接写
case (foo x y) of ...
然后在TypeConstructor
的类型构造函数上进行模式匹配,因为foo xy
没有正确的类型(它是Either String TypeConstructor
)。
但是,您可以定义一个在TypeConstructor
的类型构造函数上与模式匹配的函数,然后将其fmap
到foo xy
的结果上,如下所示。
import Control.Monad.Except (throwError)
data Type = Int Int
| Str String
deriving (Show)
foo :: Int -> String -> Either String Type
foo n s =
if n == 0
then throwError "Zero"
else return (Str s)
bar x y = fmap f (foo x y)
where
f a = case a of
Int n -> Int (n + x)
Str s -> Str (s ++ y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.