文章
关于Haskell中的fmap
在 Haskell 中,fmap 是 Functor 类型类(type class)里最核心的函数,用来把一个普通函数“映射”到“容器”或“上下文”中去
目录
- 三、Functor 定律
- fmap id ≡ id 2. **组合律(Composition):** plain text fmap (f . g) ≡ fmap f . fmap g ``` 换言之,先 fmap g 再 fmap f,等同于一次性 fmap (f . g)。
- 四、自定义 Functor
- 五、进阶技巧
- -- 只需一次 fmap fmap (+1) x -- Compose (Just [2,3,4]) 3. **`<$`**** 和 ****`void`****:** - `<$`:把容器中的所有值替换成同一个值: plain text True < [1,2,3] -- [True,True,True] ``` - `void`:丢弃值,只保留结构(等同于 `() <): ```plain text void (Just 5) -- Just () void [1,2,3] -- [(),(),()] ``` 4. **与 ****Applicative**** 的关系:** 对于任何 Applicative,它必然也是 Functor,且其 fmap与liftA/(<*>) 保持一致: ```plain text fmap f x ≡ pure f <*> x ``` 5. **fmap**** vs ****liftM****:** 在 Monad 中,liftM = fmap。不过更推荐使用 fmap/<$>`,因为它强调最小化依赖(只需 Functor 而非 Monad)。
- 六、常见陷阱