我想知道在这段代码中是否可以用警卫代替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 )
提前谢谢!
答案 0 :(得分:4)
您可以使用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 = fmap secondFunction (firstFunction xs)
fmap :: Functor f => (a -> b) -> f a -> f b
用于在函子上“映射”。现在Maybe
是一个仿函数defined as:
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a)
基本上是您在此处编写的逻辑。