if statement - Delayed evaluation in Scheme -
given following code:
(define (my-if condition iftrue iffalse) (cond (condition iftrue) (else iffalse))) '-----example1 (my-if #t (display "my if true!") (display "my if false!")) (newline) '-----example2 (my-if #t (display "my if true!") (+ 2 3))
why example 1 evaluate both parameters right away giving output of
my if true!my if false!
yet in example 2 only
my if true!
is output?
is because display
never delayed arithmetic operators are, or else?
in both cases both arguments evaluated - that's how procedures work, arguments function call evaluated before function body executed, never delayed! (unless explicitly done so).
and that's why can't implement my-if
procedure, has to special form, if
, cond
, evaluate part corresponding true condition, or else
part if none true. also, bear in mind display
prints argument on console, doesn't return value.
your second example prints message, addition got executed anyway, it's value wasn't returned because first condition true, my-if
returns value of first parameter, value returned display
call (before my-if
entered), void. instance, see outputs on console:
(my-if #t (+ 2 3) (display "my if false!"))
as expected, both parameters evaluated, first one's value returned:
my if false! ; got printed anyway 5 ; value returned `my-if`
Comments
Post a Comment