我想知道这部分代码是否可以用守卫替换 case 语句:
firstFunction :: String -> Maybe MyType
secondFunction :: MyType -> Integer
myFunction :: String -> Maybe Integer
myFunction xs = case firstFunction xs of
Nothing -> Nothing
Just x -> Just( secondFunction x )
提前谢谢您!
最佳答案
您可以使用 pattern guard [Haskell-wiki] ,例如:
myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
| otherwise = Nothing
但是你在这里所做的基本上是“fmap
”firstFunction
的结果,例如:
myFunction :: String -> Maybe Integer
myFunction xs = <b>fmap secondFunction</b> (firstFunction xs)
fmap::Functor f => (a -> b) -> f a -> f b
用于“映射”仿函数。现在也许
是一个仿函数,defined as :
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a)
这基本上就是您在此处编写的逻辑。
关于Haskell - 用防护罩替换外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53351881/