Scheme let statement

omega picture omega · Feb 18, 2013 · Viewed 9.4k times · Source

In scheme which is a functional programming language, there is no assignment statement. But in a let statement

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

You are assigning 2 to x, so why doesn't this violate the principle that there is no assignment statements in functional programming?

Answer

Óscar López picture Óscar López · Feb 18, 2013

The statement "Scheme which is a functional programming language" is incorrect. In Scheme, a functional-programming style is encouraged, but not forced. In fact, you can use set! (an assignment statement!) for modifying the value of any variable:

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

Regarding the let statement of the question, remember that an expression such as this one:

(let ((x 10))
  (+ x 3))
=> 13

... it's just syntactic sugar, and under the hood it's implemented like this:

((lambda (x)
   (+ x 3))
 10)
=> 13

Notice that a let performs one-time single assignments on its variables, so it doesn't violate any purely functional programming principle per se, the following can be affirmed of a let expression:

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

Also, quoting from Wikipedia:

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.