函数式编程的副作用 [英] Side Effects in Functional Programming

查看:95
本文介绍了函数式编程的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在《函数式编程》一书中,作者提到了以下副作用.

In a Functional Programming book the author mentions the following are the side effects.

  1. 修改变量
  2. 就地修改数据结构
  3. 在对象上设置字段
  4. 引发异常或因错误而停止
  5. 打印到控制台或阅读用户输入
  6. 读取或写入文件
  7. 在屏幕上绘画

我只是想知道如果有副作用,怎么可能编写纯功能程序而无需读取或写入文件.如果是的话,功能界实现这一目标的通用方法是什么?

I am just wondering how it is possible to write pure functional program without reading or writing to a file if they are side effects. If yes what would be the common approach in the functional world to achieve this ?

谢谢, 穆罕默德(Mohamed)

Thanks, Mohamed

推荐答案

正确回答此问题可能需要整本书(不太长).这里的要点是函数式编程旨在将逻辑描述/表示与其实际的运行时解释分开.您的功能代码只是将程序的效果表示为(不运行)为值,从而为您提供了某种抽象的语法树来描述您的计算.您代码的不同部分(通常称为解释器)将采用这些值并懒惰地运行实际效果.那部分不起作用.

Properly answering this question requires likely an entire book (not too long). The point here is that functional programming is meant to separate logic description / representation from it's actual runtime interpretation. Your functional code just represents (doesn't run) the effects of your program as values, giving you back some kind of abstract syntax tree that describes your computation. A different part of your code (usually called the interpreter) will take those values and lazily run the actual effects. That part is not functional.

如何编写以任何方式都有用的纯函数程序?这不可能.纯功能程序只会加热CPU.它需要一个不实际的部分(解释器)来实际写入磁盘或网络. 以这种方式进行操作有几个重要的优点.纯功能部分易于测试(测试纯功能很容易),并且相对透明性质的纯函数使在本地对代码的理解变得容易,从而使开发过程成为一个整体减少越野车,提高生产力.它还提供了处理传统上模糊的防御性代码的优雅方法.

How is it possible to write a pure functional program that is useful in any way? It is not possible. A pure functional program only heats up the CPU. It needs an impure part (the interpreter) that actually writes to disk or to the network. There are several important advantages in doing it that way. The pure functional part is easy to test (testing pure functions is easy), and the referentially transparent nature of pure functions makes easy to reason about your code locally, making the development process as a whole less buggy and more productive. It also offers elegant ways to deal with traditionally obfuscated defensive code.

那么在功能界实现副作用的常见方法是什么?如前所述,使用值表示它们,然后编写解释这些值的代码.可以在这些博客文章系列中的.

So what is the common approach in the functional world to achieve side effects? As said, representing them using values, and then writing the code that interprets those values. A really good explanation of the whole process can be found in these blog post series.

这篇关于函数式编程的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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