zoukankan      html  css  js  c++  java
  • 副作用与纯函数--纯函数化是副作用处理的基本方案

    一、纯函数:

    函数:(只)参量依赖、解决确定、环境无修改。

    函数与输入、输出、环境的关系。

    二、副作用

    (Side Effect)是指函数或者表达式的行为依赖于外部世界。具体可参照Wiki上的定义,副作用是指

    1)函数或者表达式修改了它的SCOPE之外的状态

    2)函数或者表达式除了返回语句外还与外部世界或者它所调用的函数有明显的交互行为

    https://www.cnblogs.com/racaljk/p/7822281.html

    函数的结果只依赖输入,并且解决确定,并且对环境没有影响。

    三、纯函数

    http://www.ayqy.net/blog/函数式编程中如何处理副作用?/

    引用透明(referential transparency)

    • 可推理(reason about your code)

    基础语法_Haskell笔记1

    有些副作用是不可避免且至关重要的输出:显示到Console、发送给打印机、写入数据库等

    • 输出:显示到Console、发送给打印机、写入数据库等
    • 输入:从输入设备取得用户输入、从网络请求信息等
    •    
    • http://www.ayqy.net/blog/函数式编程中如何处理副作用?/

    环境、计算、修改、数据、流程。

    副作用不能避免,只能修改。

    异步编程和异常都对有副作用的外部因素产生了引用。

    四、副作用

    所谓"副作用"(side effect),指的是函数内部与外部互动(最典型的情况,就是修改全局变量的值),产生运算以外的其他结果。

    函数式编程强调没有"副作用",意味着函数要保持独立,所有功能就是返回一个新的值,没有其他行为,尤其是不得修改外部变量的值。

    In computer science, a function or expression is said to have a side effect if it 

    modifies some state outside its scope or 

    has an observable interaction with its calling functions or 

    the outside world besides returning a value. 

    For example, a particular function might modify a global variable or static variable, modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions. In the presence of side effects, a program's behaviour may depend on history; that is, the order of evaluation matters. Understanding and debugging a function with side effects requires knowledge about the context and its possible histories.[1][2]

    Side effects are the most common way that a program interacts with the outside world (people, filesystems, other computers on networks). But the degree to which side effects are used depends on the programming paradigm. Imperative programming is known for its frequent utilization of side effects.

    副作用就是对所处的环境有改变。

    既然有改变多次调用有副作用的语句或函数,结果不一定保持一致。而如果是无副作用的语句或函数,调用多次结果是一致的。

    副作用的对立面是纯函数。

    纯函数的返回值是由参数决定的,例如 Math.floor() ,给定参数,所能得到的返回值是一定的

    而副作用就是,一个函数它的行为不只依赖于参数,也不只是根据参数给出返回值。

    例如 redux 里的 reducer ,就是利用了纯函数,把复杂的程序状态管理起来,变得可预期、可扩展、可维护、可测试。

    副作用的意思就是说,我光调用这个函数,然后不去管他的返回值,结果他却给我的其它地方造成了影响(包括但不限于修改全局变量)。在编译原理里面,如果你什么都不说的话,那么函数缺省就是为了生成返回值而服务的,其它什么都不会干。

    https://www.zhihu.com/question/27820488

    五、引用透明

    引用透明

    Referential transparency and referential opacity are properties of parts of computer programs. An expression is called referentially transparent if it can be replaced with its corresponding value without changing the program's behavior.[1] This requires that the expression is pure, that is to say the expression value must be the same for the

  • 相关阅读:
    作业01
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言II博客作业04
    C语言II—作业03
    C语言II博客作业02
    C语言II博客作业01
  • 原文地址:https://www.cnblogs.com/feng9exe/p/10846107.html
Copyright © 2011-2022 走看看