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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With