Pregunta

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 with(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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top