為什么這會 fmap (replicate 3) Just "JOHN"回傳 this [Just "JOHN",Just "JOHN",Just "JOHN"]?我知道這 fmap (replicate 3) Just "JOHN"與 等價 fmap (replicate 3) Just $ "JOHN",但為什么它甚至可以編譯?我們如何申請fmap甚至
Just不是具體型別的?
uj5u.com熱心網友回復:
仿函式f是一個型別建構式,它帶有一個關聯函式fmap,它把一個型別的函式“提升”為一個型別a -> b的函式f a -> f b。
Maybe和(部分應用的函式建構式)都是(->) r函子。
-- When possible, apply the function to the wrapped value
-- and wrap the result. Otherwise, return Nothing
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)
-- Compose the two functions
instance Functor ((->) r) where
fmap f g = f . g
replicate 3 :: a -> [a]您的運算式在兩個函式和上使用函式實體Just :: a -> Maybe a:
fmap (replicate 3) Just "JOHN" == (replicate 3) . Just $ "JOHN"
== (replicate 3) (Just "JOHN")
== [Just "JOHN", Just "JOHN", Just "JOHN"]
您可能打算replicate 3使用實體映射value Just "JOHN" :: Maybe String。Maybe
fmap (replicate 3) (Just "JOHN") == Just (replicate 3 "JOHN")
== Just ["JOHN", "JOHN", "JOHN"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416356.html
標籤:
下一篇:遞回函式中缺少模式匹配
