簡體   English   中英

Haskell - 用警衛代替案件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM