Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of begin in Scheme?

Tags:

scheme

I don't understand how using the begin keyword is useful in writing a sequence of expressions in Scheme.

I mean, when I write expressions, aren't they supposed to be evaluated from left to right? So, why must I still include a begin keyword?

I read that begin is supposed to eliminate side-effects from input and output. Can anyone give me a situation where begin is necessary?

like image 772
Guppy_00 Avatar asked Apr 09 '16 13:04

Guppy_00


1 Answers

begin is necessary every time you need several forms when the syntax allows only one form. For instance, if you need to increment a variable y each time you use it:

(+ x 
   (begin (set! y (+ y 1)) y) 
   z)

If you omit the begin, then you simply could not write this expression (in Common Lisp, the same expression could be written as (+ x (incf y) z)).

Note that (set! x y) does not return a value. This is the reason we need to use begin, since (begin f1 f2 ... fn) evaluates f1 ... fn in turn and then returns the value of fn. So, (begin (set! y (+ y 1)) y) increments the value of y and the y is evaluated, and then its new value is returned.

begin is normally used when there is some side-effect.

like image 136
Renzo Avatar answered Nov 10 '22 02:11

Renzo