Haskell-用防护装置更换外壳
我想知道,在这部分代码中,是否可以用guards替换case语句:Haskell-用防护装置更换外壳,haskell,Haskell,我想知道,在这部分代码中,是否可以用guards替换case语句: firstFunction :: String -> Maybe MyType secondFunction :: MyType -> Integer myFunction :: String -> Maybe Integer myFunction xs = case firstFunction xs of Nothing -> Nothing Just x -> Jus
firstFunction :: String -> Maybe MyType
secondFunction :: MyType -> Integer
myFunction :: String -> Maybe Integer
myFunction xs = case firstFunction xs of
Nothing -> Nothing
Just x -> Just( secondFunction x )
提前谢谢你 您可以使用一个
fmap::函子f=>(a->b)->fa->fb
用于“映射”函子。现在可能是一个函子,:
这基本上就是你在这里写的逻辑。我认为你不需要守卫,只要fmap
:fmap第二个函数(第一个函数x)
myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
| otherwise = Nothing
myFunction :: String -> Maybe Integer
myFunction xs = fmap secondFunction (firstFunction xs)
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)