为什么应用仿函数有副作用,但仿函数不能? [英] Why can applicative functors have side effects, but functors can't?

查看:319
本文介绍了为什么应用仿函数有副作用,但仿函数不能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感觉这个问题相当愚蠢,但是我一直在脑海里想了一会儿,找不到任何答案。

所以问题是:为什么应用仿函数有副作用,但仿函数不能?

也许他们可以,我从来没有注意到...?

解决方案

这个答案有点过分简化,但是如果我们定义副作用是受以前计算影响的计算,很容易看到 Functor typeclass对于副作用是不够的,因为没有办法链接多个计算。

  class Functor f其中
fmap ::(a - > b) - > f a - > fb

一个函子可以做的唯一事情就是通过一些纯函数来改变计算的最终结果 a - > b



然而,一个应用仿函数增加了两个新函数 pure <>

  class Functor f =>应用f其中
pure :: a - > f a
(*):: f(a - > b) - > f a - > fb



< /> 是这个关键的区别在于,它允许我们链接两个计算:
f(a - > b)(产生函数的计算)和 fa 计算
提供函数应用的参数。使用纯净<> 它可能是
来定义例如

 (*>):: fa  - > f b  - > fb 

它简单地链接两个计算,放弃第一个
的最终结果可能会使用副作用)。

所以简而言之,它是连接计算的能力,这是计算中可变状态等效果的最低要求。


I'm feeling rather silly asking this question, but it's been on my mind for a while and I can't find any answers.

So the question is: why can applicative functors have side effects, but functors can't?

Maybe they can and I've just never noticed...?

解决方案

This answer is a bit of an over-simplification, but if we define side effects as computations being affected by previous computations, it's easy to see that the Functor typeclass is insufficient for side effects simply because there is no way to chain multiple computations.

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

The only thing a functor can do is to alter the end result of a computation via some pure function a -> b.

However, an applicative functor adds two new functions, pure and <*>.

class Functor f => Applicative f where
    pure   :: a -> f a
    (<*>)  :: f (a -> b) -> f a -> f b

The <*> is the crucial difference here, since it allows us to chain two computations: f (a -> b) (a computation which produces a function) and f a a computation that provides the parameter to which the function is applied. Using pure and <*> it's possible to define e.g.

(*>) :: f a -> f b -> f b

Which simply chains two computations, discarding the end result from the first one (but possibly applying "side effects").

So in short, it's the ability to chain computations which is the minimum requirement for effects such as mutable state in computations.

这篇关于为什么应用仿函数有副作用,但仿函数不能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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