是纯粹的功能无法找到的一切副作用? [英] Are side effects everything that cannot be found in a pure function?

查看:130
本文介绍了是纯粹的功能无法找到的一切副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以肯定的是,下面的二分法是可行的:

每个给定的函数都是


  • 要么纯净

  • 或有副作用
    / b>

    如果是这样, (函数)是任何在纯函数中都找不到的东西。

    解决方案

    这很大程度上取决于定义你选择。说一个函数是不纯是绝对公平的。纯函数总是返回相同的结果并且不会修改环境。一个不纯的函数在重复执行时可能会返回不同的结果(这可能是由于对环境做了某些事情造成的)。

    是否有杂质副作用?我不会这么说 - 一个函数可以取决于它执行的环境中的某些东西。这可能是读取一些配置,GPS位置或从互联网上读取数据。这些并不是真正的副作用,因为它不会对世界做任何事情。



    我认为有两种不同的杂质:




    • 输出杂质是函数对世界做出某些事情的时候。在Haskell中,这是使用monads建模的 - 一个不纯的函数 a - > b 实际上是一个函数 a - > M b 其中 M 捕获了它对世界所做的其他事情。


    • 输入杂质是函数需要环境中的某些东西时。一个不纯的函数 a - > b 可以被建模为一个函数 C a - > b >


    • 类型 C 从环境中捕获了该函数可以访问的其他内容。 / ul>

      Monads和输出杂质当然更为人所知,但我认为输入杂质同样重要。我写了关于输入杂质的博士论文,我称其为,所以我可能会有偏颇的答案。


      Is it safe to say that the following dichotomy holds:

      Each given function is

      • either pure
      • or has side effects

      If so, side effects (of a function) are anything that can't be found in a pure function.

      解决方案

      This very much depends on the definitions that you choose. It is definitely fair to say that a function is pure or impure. A pure function always returns the same result and does not modify the environment. An impure function can return different results when it is executed repeatedly (which can be caused by doing something to the environment).

      Are all impurities side-effects? I would not say so - a function can depend on something in the environment in which it executes. This could be reading some configuration, GPS location or reading data from the internet. These are not really "side-effects" because it does not do anything to the world.

      I think there are two different kinds of impurities:

      • Output impurity is when a function does something to the world. In Haskell, this is modelled using monads - an impure function a -> b is actually a function a -> M b where M captures the other things that it does to the world.

      • Input impurity is when a function requires something from the environment. An impure function a -> b can be modelled as a function C a -> b where the type C captures other things from the environment that the function may access.

      Monads and output impurities are certainly better known, but I think input impurities are equally important. I wrote my PhD thesis about input impurities which I call coeffects, so I this might be a biased answer though.

      这篇关于是纯粹的功能无法找到的一切副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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