gpt4 book ai didi

functional-programming - 方案出租声明

转载 作者:行者123 更新时间:2023-12-04 08:41:48 24 4
gpt4 key购买 nike

在作为一种功能编程语言的方案中,没有赋值语句。
但是在let语句中

(let ((x 2))
(+ x 3))

您正在将 2分配给 x,那么为什么这不违反函数式编程中没有赋值语句的原则呢?

最佳答案

语句“是一种功能编程语言的方案”是不正确的。在Scheme中,鼓励但不强制使用函数式编程样式。实际上,您可以使用set!(赋值语句!)来修改任何变量的值:

(define x 10)
(set! x (+ x 3))
x
=> 13

关于问题的 let语句,请记住这样的表达式:
(let ((x 10))
(+ x 3))
=> 13

...只是语法糖,在幕后这样实现:
((lambda (x)
(+ x 3))
10)
=> 13

请注意, let在其变量上执行一次 single assignments,因此它本身没有违反任何纯函数式编程原理,可以确认 let表达式为以下内容:

An evaluation of an expression does not have a side effect if it does not change an observable state of the machine, and produces same values for same input



另外,引自维基百科:

Impure functional languages provide both single assignment as well as true assignment (though true assignment is typically used with less frequency than in imperative programming languages). For example, in Scheme, both single assignment (with let) and true assignment (with set!) can be used on all variables, and specialized primitives are provided for destructive update inside lists, vectors, strings, etc.

关于functional-programming - 方案出租声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14943681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com