开发者

What's the expression equivalent of the Assignment statement called?

开发者 https://www.devze.com 2023-04-06 23:55 出处:网络
In imperative programming, using statements, you do stuff like: a = 10 b = a * 2 print a # 20 I have been thinking that the equivalent, in expressions, should be something like this:

In imperative programming, using statements, you do stuff like:

a = 10
b = a * 2
print a # 20

I have been thinking that the equivalent, in expressions, should be something like this:

print wi开发者_StackOverflowth(a=10){with(b=a*2){return b}}

This being written in butchered python, but it shouldn't matter, it should illustrate what i mean. Rather than changing the state of the variable in the program (which then remains changed forever), it changes it in the block scope, for any expressions within that scope.

There probably is a name for this sort of thing. I don't know any pure-functional languages, but I imagine this sort of thing would be rather very useful for calculating temporary values when assignment-statements don't exist. Does anyone know what it's called, what languages have this inbuilt, and where I can find more information about it?


Well, there are let-bindings:

let a = 10 in
let b = a * 2 in
b

Those are present in most functional languages, although sometimes with different syntax (the most obvious deviant I know of being lisp, which uses (let ((a 10)) (let ((b (* a 2))) b)); there's also letrec and let* which place different restrictions on what the expressions being assigned can refer to). One can also create multiple bindings in a single let.

Note that formally, it doesn't change the variable for a brief period of time but introduces a new scope, with new variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号