简体   繁体   English

Haskell - 用警卫代替案件

[英]Haskell - replace case with guards

i'd like to know if in this portion of code is possible to replace the case statement with guards: 我想知道在这部分代码中是否可以用守卫替换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 )

Thank you in advance! 先感谢您!

You could use a pattern guard [Haskell-wiki] , like: 您可以使用模式防护 [Haskell-wiki] ,如:

myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
              | otherwise = Nothing

But what you here do is basically " fmap " the result of firstFunction , like: 但是,你在这里做什么基本上是“ fmap ”的结果firstFunction ,如:

myFunction :: String -> Maybe Integer
myFunction xs = fmap secondFunction (firstFunction xs)

fmap :: Functor f => (a -> b) -> fa -> fb is used to "map" over a functor. fmap :: Functor f => (a -> b) -> fa -> fb用于在fmap :: Functor f => (a -> b) -> fa -> fb上“映射”。 Now Maybe is a functor, defined as : 现在Maybe是一个算子, 定义为

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

which is basically the logic you wrote here. 这基本上就是你在这里写的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM