Why isn't this Racket code ending?
I am reading about lazy evaluation and do not understand how they took the main example.
#lang racket
(define (bad-if x y z)
(if x y z))
(define (factorial-wrong x)
(bad-if (= x 0)
1
(* x (factorial-wrong (- x 1)))))
(factorial-wrong 4)
I am a little confused as to why this program never ends. I know the following code works really well:
(define (factorial x)
(if (= x 0)
1
(* x (factorial (- x 1)))))
(factorial 4)
So I guess it has something to do with scope. I've tried step by step debugging and factorial-wrong performs the recursion function even when x is mapped to 0.
source to share
Standard if
(if test-expr then-expr else-expr)
will evaluate only then-expr
or else-expr
, depending on test-expr
, because this one if
is either a special form or a syntactic extension on a special form, which means it does not conform to the normal evaluation rules.
bad-if
, on the other hand, is a standard procedure. In this case, the schema evaluates both expressions first , since they are procedure parameters bad-if
before actually executing bad-if
. So even at x = 0 there will be an estimate (* x (factorial -1))
, which in turn will estimate (* x (factorial -2))
, etc. In an endless loop.
source to share