Lisp racket: a comparison between new-if and if

(define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter(improve guess x) x))) (define (improve guess x) (average guess(/ x guess))) (define (average xy) (/ (+ xy) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.0001)) (define (square x) (* xx)) (define (sqrt-g x) (sqrt-iter 1.0 x)) 

This is a program for sqrt. And the question is when you try to use new-if to replace if with new-if.

 (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter(improve guess x) x))) 

It is new if

  (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) 

My opinion is the result of two programs that will be the same. because new-if and if can give the same results.

However, a new one - if proven wrong, because it was a dead circle when I tried.

So why?

+4
source share
2 answers

new-if is a function. All function arguments are evaluated before the function is called. But sqrt-iter is a recursive function, and you need to avoid the recursive call when the argument is already good enough.

The built-in if is syntax and only evaluates the then-branch or else-branch, depending on the value of the condition.

You can use the macro to write new-if .

+8
source

This is a great example of demonstrating an algebraic step! In the algebraic pedometer, you can see how the course of calculations differs from your expectation. Here you should pay attention to differences in the assessment of, say, (new-if 1 2 3) and (if 1 2 3).

If you haven't tried an algebraic stepper before, see this answer to see how it looks.

+3
source

Source: https://habr.com/ru/post/1434525/


All Articles