我想知道在这部分代码中是否可以用守卫替换 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 维基] https://wiki.haskell.org/Pattern_guard, like:
myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
| otherwise = Nothing
但你在这里所做的基本上是“fmap
“ 的结果firstFunction
, like:
myFunction :: String -> Maybe Integer
myFunction xs = fmap secondFunction (firstFunction xs)
fmap :: Functor f => (a -> b) -> f a -> f b
用于“映射”函子。现在Maybe
是一个函子,定义为 http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Base.html#line-836:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
这基本上就是你在这里写的逻辑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)