haskell - 基于 `fmap` 的 `<*>` 的实现对于 Maybe applicative 是特殊的还是可以推广到其他 applicative?
问题描述
在 Maybe applicative 中,<*>
可以基于fmap
. 它是偶然的,还是可以推广到其他应用程序?
(<*>) :: Maybe (a -> b) -> Maybe a -> Maybe b
Nothing <*> _ = Nothing
(Just g) <*> mx = fmap g mx
谢谢。
解决方案
不能一概而论。Functor
实例是唯一的:
instance Functor [] where
fmap = map
但是Applicative
同一类型的构造函数可以有多个有效实例。
-- "Canonical" instance: [f, g] <*> [x, y] == [f x, f y, g x, g y]
instance Applicative [] where
pure x = [x]
[] <*> _ = []
(f:fs) <*> xs = fmap f xs ++ (fs <*> xs)
-- Zip instance: [f, g] <*> [x, y] == [f x, g y]
instance Applicative [] where
pure x = repeat x
(f:fs) <*> (x:xs) = f x : (fs <*> xs)
_ <*> _ = []
在后者中,我们既不想将左侧参数中的任何单个函数应用于右侧的所有元素,也不想将左侧的所有函数应用于右侧的任何单个元素,从而变得fmap
无用。
推荐阅读
- c# - if else 语句中 file.exist 语句的 C# 问题
- javascript - 如何立即更改选取框 onclick 的方向
- c# - 执行超时已过期。在操作完成之前经过的超时时间或服务器在 C# 中没有响应
- robotframework - 我无法使用 Robot Framework 中的变量参数化变量
- java - 使用泛型方法进行 Java 类型擦除
- python-3.x - 无法腌制 pydicom 数据集,不知道为什么
- amazon-web-services - 对于新用户如何创建和共享私钥?
- spring - Spring boot 2 在安全拦截器之前添加拦截器
- laravel-5 - Laravel Eloquent 如何选择和操作数据透视表中的行?
- javascript - wrapper.instance() 上的反应测试失败