[英]Haskell - replace case 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 )
先感謝您!
您可以使用模式防護 [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) -> fa -> fb
用於在fmap :: Functor f => (a -> b) -> fa -> fb
上“映射”。 現在Maybe
是一個算子, 定義為 :
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (fa)
這基本上就是你在這里寫的邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.