[英]Why does the Applicative instance for Maybe give Nothing when function is Nothing in <*>
[英]Why does applicative work default only for Maybe
我試圖理解為什么對於像Maybe
這樣的某些函子,應用函子默認情況下會工作(無需實現),而對於其他函子卻不起作用:
例:
Just (+3) <*> (Just 3)
“開箱即用”-> 6
Left (+3) <*> Left 3
不起作用
即使我聲明Either Int Int
Just (+3) <*> Left 4
也不起作用。
我假設在99%的情況下,當處理成對的: (f (a->b) , fa)
您必須自己實現所需的行為( 笛卡爾乘積 (f (a->b)) X (fa)
),並且第一個例子是開箱即用的簡單東西。
示例對於(Maybe (a->b) , Either cd)
我們需要涵蓋所有4種情況:
Just - Left Just - Right Nothing - Left Nothing -Right
我在這個假設中正確嗎?
Either
的Applicative
實例定義為:
instance Applicative (Either e) where ...
給定的類型(<*>)
是Applicative f => f (a -> b) -> fa -> fb
為Either
是:
Either e (a -> b) -> Either e a -> Either e b
Left
的類型為e -> Either ea
所以Left (+3)
的類型為
Num a => Either (a -> a) b
Left 3
的類型是:
Num a => Either a b
這導致Left (+3) <*> Left 3
為(Num a, Num (a -> a)) => Either (a -> a) b
都不是您想要的。
由於類型b
包含要操作的函數和值,因此使用Right
構造函數確實可行:
Right (+3) <*> Right 3
=> Right 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.