关于 haskell 中的一些基本函子
About some basic functor in haskell
为什么这个 fmap (replicate 3) Just "JOHN"
return 这个 [Just "JOHN",Just "JOHN",Just "JOHN"]
?我知道 fmap (replicate 3) Just "JOHN"
等同于 fmap (replicate 3) Just $ "JOHN"
,但为什么它甚至可以编译?我们如何将 fmap
应用于
Just
这甚至不是具体类型?
仿函数 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
映射到 值 Just "JOHN" :: Maybe String
,利用 Maybe
实例。
fmap (replicate 3) (Just "JOHN") == Just (replicate 3 "JOHN")
== Just ["JOHN", "JOHN", "JOHN"]
为什么这个 fmap (replicate 3) Just "JOHN"
return 这个 [Just "JOHN",Just "JOHN",Just "JOHN"]
?我知道 fmap (replicate 3) Just "JOHN"
等同于 fmap (replicate 3) Just $ "JOHN"
,但为什么它甚至可以编译?我们如何将 fmap
应用于
Just
这甚至不是具体类型?
仿函数 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
映射到 值 Just "JOHN" :: Maybe String
,利用 Maybe
实例。
fmap (replicate 3) (Just "JOHN") == Just (replicate 3 "JOHN")
== Just ["JOHN", "JOHN", "JOHN"]