Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme let statement

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?

like image 541
omega Avatar asked Feb 18 '13 19:02

omega


People also ask

What is the example of let statement?

Valid LET statements. LET a = 5; LET b = 6; LET c = 10; LET a,b = 10,c+d; LET a,b = (SELECT cola,colb FROM tab1 WHERE cola=10); LET d = func1(x,y); IBM® Informix® allows you to assign a value to an opaque-type variable, a row-type variable, or a field of a row type.

What is let form in Scheme?

Scheme has a special form which allows you to introduce local variables into a function. (let bindings body) Here body is a sequence of expressions and bindings has the form: ( (variable1 init1) ...)

What is the let statement used for?

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables.

What is a Scheme expression?

A Scheme expression is a construct that returns a value, such as a variable reference, literal, procedure call, or conditional. Expression types are categorized as primitive or derived. Primitive expression types include variables and procedure calls.


1 Answers

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.

like image 162
Óscar López Avatar answered Oct 08 '22 02:10

Óscar López