基于fmap的< *>的实现是否可能是可应用的,还是可以推广到其他应用? [英] Is the implementation of `<*>` based on `fmap` special to Maybe applicative or can it be generalized to other applicatives?

查看:75
本文介绍了基于fmap的< *>的实现是否可能是可应用的,还是可以推广到其他应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可能的情况下,可以基于fmap实现<*>.是偶然的,还是可以推广到其他应用程序?

In Maybe applicative, <*> can be implemented based on fmap. Is it incidental, or can it be generalized to other applicative(s)?

(<*>)   ::  Maybe   (a  ->  b)  ->  Maybe   a   ->  Maybe   b
Nothing <*> _   =   Nothing
(Just   g)  <*> mx  =   fmap    g   mx

谢谢.

另请参阅在适用情况下,如何用fmap_i,i = 0,1,2,...`来表示< *?

推荐答案

它不能一概而论. Functor实例是唯一的:

It cannot be generalized. A Functor instance is unique:

instance Functor [] where
    fmap = map

,但是对于同一类型构造函数,可以有多个有效的Applicative实例.

but there can be multiple valid Applicative instances for the same type constructor.

-- "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)
    _ <*> _ = []

在后者中,我们既不想将left参数中的任何单个函数应用到右边的所有元素,也不想将左边的所有函数应用到右边的任何单个元素,从而使fmap没有用.

In the latter, we neither want to apply any single function from the left argument to all elements of the right, nor apply all the functions on the left to any single element on the right, making fmap useless.

这篇关于基于fmap的&lt; *&gt;的实现是否可能是可应用的,还是可以推广到其他应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆