首页 > 解决方案 > 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 )

先感谢您!

标签: haskell

解决方案


您可以使用模式保护[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用于在仿函数上“映射”。NowMaybe是一个仿函数,定义为

instance Functor Maybe  where
    fmap _ Nothing = Nothing
    fmap f (Just a) = Just (f a)

这基本上就是你在这里写的逻辑。


推荐阅读