跳到主要内容

函子

Functor

定义

class Functor f where
fmap :: (a -> b) -> f a -> f b

意思是现在有:

  1. 一个将a类型处理成b类型的函数
  2. 一个包含a类型的f类型容器

现在构造一个函数,它的功能是使用函数将原容器转换为包含b类型的f类型容器
比如Java中的Streammap方法
可以将一个列表中的每个元素单独处理,然后将每个元素放到一个新的列表中

我们将这样“每个元素单独处理”的函数记作fmap
将能够被fmap处理的类型称作函子(比如Java中的列表)

Identity

恒等函子
一个包装值、对值应用函数的简单容器

newtype Identity a = Identity { runIdentity :: a }

instance Functor Identity where
fmap f (Identity a) = Identity (f a)

Const

常量函子

newtype Const m a = Const { getConst :: m }

instance Functor (Const m) where
fmap _ (Const v) = Const v

其中,a幻影类型(phantom type)
表现为一个额外的无用参数
在表面上它没什么用,但它会被类型检查识别到
它是一种技巧,可以用来标识一个量是否被验证或者处于什么状态

IO

将f应用于IO操作的结果,得到一个新的IO操作

instance Functor IO where
fmap f action = do
result <- action
return (f result)

Lens

透镜组
被用于生成一个访问函数

type Lens s a = forall f. Functor f => (a -> f a) -> s -> f s
data Position = Position {x :: Int, y :: Int} deriving (Eq, Show)
type Lens' s a = forall f. (Functor f) => (a -> f a) -> s -> f s

xLens :: Lens' Position Int
xLens f p = fmap (\x' -> p{x = x'}) (f (x p))

p1 = Position 1 2

main = print (runIdentity (xLens (Identity . (+ 1)) p1)) -- 输出p1的x加1的新Position