Wednesday, 5 December 2018

Block Structure (Square Root) - LISP

Block Structure - LISP


Now the style in which we have been coding until now , is a bit dangerous if we are talking about large and complex program as our coding style may lead to ambiguity between different programmer's function nomenclature. suppose one programmer name's  a function 'addup' which add's 2 numbers and then add's it with the multiplication of two numbers : (x + y) + (x * y) and suppose another function similarly names some other routine 'addup' which adds 2 numbers two times like (x + y) + (x + y) or 2* (x + y) now during execution , there may occur some ambiguity which may lead to unintended consequences , so we use block structures in which the not so common functions are defined inside the main function which we are using , like in previous square-root and cube-root example good enough?  and improve are not common functions so we can use the block structure as follows: 

First defining the common functions, square of a number and average of 2 numbers...

(define (square x)(* x x))

(define (average x y)(/ (+ x y) 2))

Now defining the square-root function in a block structure method : -

(define (sqr-root guess x)
    (define (good-guess)(<(abs(- (square guess) x)) 0.001))
    (define (improve)(average guess (/ x guess)))
    (if(good-guess) guess (sqr-root (improve) x)))

In above code, we first know that we need to pass the guess and the number of which we want the square root : so we started by:
(define (sqr-root guess x)

Now we know from original method that sqr-root function looks like this :
(define (sqr-root guess x)(if (good-guess guess x) guess (sqr-root (improve guess x) x))

So we know that we will require good-guess and an improve function ,  so we define good-guess function as:
(define (good-guess) (<(abs(-(square guess) x))0.001))

we didn't passed the parameters guess and x to the good-guess function as we are defining the good-guess function inside of sqr-root function so we don't need to pass the parameters since inside the function sqr-root we already know the value of guess and x.
similarly , we defined improve inside the sqr-root function as :

(define (improve) (average guess (/x guess)))

Now let us see how the program will look like in the terminal :

>(define (square x)(* x x))
>(define (average x y)(/ (+ x y) 2))
>(define (sqr-root guess x)
    (define (good-guess)(<(abs(- (square guess) x)) 0.001))
    (define (improve)(average guess (/ x guess)))
    (if(good-guess) guess (sqr-root (improve) x)))

Lets run the program and try the function sqr-root out:
>(sqr-root 1.0 4)
2.0000000929222947

Written By,
Sarvesh Bhatnagar


No comments:

Post a Comment