Haskell-用护卫替换箱子

时间:2018-11-17 13:56:40

标签: haskell

我想知道在这段代码中是否可以用警卫代替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 )

提前谢谢!

1 个答案:

答案 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)

基本上是您在此处编写的逻辑。