函数式编程会避免状态吗? [英] Does functional programming avoid state?

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

问题描述

根据维基百科:函数式编程是一种将计算视为对数学的评估的编程范例.功能,并避免状态和易变数据. (强调我的).

According to wikipedia: functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. (emphasis mine).

这是真的吗?我个人的理解是,从某种意义上说,编程本质上是将函数(转换)应用于给定状态以获得转换后的状态,这使状态更加明确.特别是,像monads这样的构造使您可以通过函数显式地承载状态.我也不认为任何编程范例都可以完全避免状态.

Is this really true? My personal understanding is that it makes the state more explicit, in the sense that programming is essentially applying functions (transforms) to a given state to get a transformed state. In particular, constructs like monads let you carry the state explicitly through functions. I also don't think that any programming paradigm can avoid state altogether.

那么,维基百科的定义是对还是错?如果错了,那么定义函数式编程的更好方法是什么?

So, is the wikipedia definition right or wrong? And if it is wrong what is a better way to define functional programming?

编辑:我想这个问题的中心点是什么是状态?您是否理解状态是变量或对象属性(可变数据)还是不可变数据?还说明吗?举个例子(在F#中):

Edit: I guess a central point in this question is what is state? Do you understand state to be variables or object attributes (mutable data) or is immutable data also state? To take an example (in F#):

let x = 3
let double n = 2 * n
let y = double x
printfn "%A" y

您会说这段代码是否包含状态?

would you say this snippet contains state or not?

编辑2 :感谢大家的参与.我现在认为这个问题更多是语言上的差异,因为state一词的使用在一个社区与另一个社区之间是不同的,正如Brian在评论中提到的那样.特别是,函数式编程社区中的许多人(主要是Haskellers)将state解释为带有某种动态状态,例如随时间变化的信号. state有限状态机代表性状态传输无状态网络协议中的其他用途可能意味着不同的事情.

Edit 2: Thanks for everyone for participating. I now understand the issue to be more of a linguistic discrepancy, with the use of the word state differing from one community to the other, as Brian mentions in his comment. In particular, many in the functional programming community (mainly Haskellers) interpret state to carry some state of dynamism like a signal varying with time. Other uses of state in things like finite state machine, Representational State Transfer, and stateless network protocols may mean different things.

推荐答案

我认为您只是在使用术语州"以一种不寻常的方式.如果考虑将1和1相加得到2是有状态的,那么可以说函数式编程包含状态.但是,当大多数人说状态"时,它们的意思是存储和更改值,以便调用一个函数可能会使事情与调用该函数之前有所不同,并且使用相同的输入再次调用该函数可能不会得到相同的结果.

I think you're just using the term "state" in an unusual way. If you consider adding 1 and 1 to get 2 as being stateful, then you could say functional programming embraces state. But when most people say "state," they mean storing and changing values, such that calling a function might leave things different than before the function was called, and calling the function a second time with the same input might not have the same result.

  • 1 + 1的结果
  • 由"s"组成的字符串以"pool"开头
  • 给定矩形的面积
  • 增加计数器
  • 从数组中删除元素
  • 将矩形的宽度设置为现在的两倍

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

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