![](/img/trans.png)
[英]Why can't I use 'isJust' in the lambda function in `foldr`?
[英]Apply a function only if isJust
我正在尋找一種慣用的方式
moveMaybeCreature Nothing world = world
moveMaybeCreature (Just creature) world = moveCreature creature world
或者換句話說
if isJust c
then doSomething (fromJust c) w
else w
我以為我可以這樣做:
moveMaybeCreature c w = foldr moveCreature w (maybeToList c)
我可以在不必將Maybe Creature
轉換為[Creature]
嗎?
只要world
類型和moveCreature (fromJust c) world
相同,你就可以做到這一點。 您可以使用maybe
從Data.Maybe
。
moveMaybeCreature = maybe id moveCreature
你模式匹配的第一種方式應該也可以正常工作。
我推薦使用maybe
函數。 你提出這個問題是正確的,因為這個一般的經驗法則(不僅適合你,而且適合任何新人閱讀):類似Maybe Foo -> Bar
或Maybe Foo -> Maybe Bar
的函數是直接定義的Haskell中的代碼味道 。 你幾乎從不想寫一個以Maybe Foo
為參數的函數; 你想要一個只需要Foo
的函數,並使用一個更高階的函數來使它適應Maybe Foo
。
假設你有一個函數f' :: Maybe Foo -> Maybe Bar
。 這通常可以重構為:
f :: Foo -> Bar
和fmap f :: Maybe Foo -> Maybe Bar
; f :: Foo -> Maybe Bar
和(>>=f) :: Maybe Foo -> Maybe Bar
第一種情況有效,因為這是Maybe
的Functor
實例:
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)
-- or this:
-- fmap f = maybe Nothing (Just . f)
第二種情況有效,因為這是Maybe
的Monad
實例:
instance Monad Maybe where
return = Just
Nothing >>= f = Nothing
(Just x) >>= f = f x
-- or this:
-- mx >>= f = maybe Nothing f mx
這是另一個選項,更接近原始代碼:
import qualified Data.Foldable as F
moveMaybeCreature = flip (F.foldr moveCreature)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.