[英]Haskell - replace case with guards
我想知道在这部分代码中是否可以用守卫替换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 )
先感谢您!
您可以使用模式防护 [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 = fmap secondFunction (firstFunction xs)
fmap :: Functor f => (a -> b) -> fa -> fb
用于在fmap :: Functor f => (a -> b) -> fa -> fb
上“映射”。 现在Maybe
是一个算子, 定义为 :
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (fa)
这基本上就是你在这里写的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.