Thursday, 29 November 2018

Simple Procedures - LISP

Simple Procedures - LISP (Scheme)


In this post we will see how to define some procedures and use them.

Square:

Square of a number is the number time's number itself. Lets see how we can define the procedure to find a square of a number.

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

yes its that simple, and can be read as: define square which takes 1 argument x, and returns x * x. 

Now suppose we want to find the square of 4, we would simple type the following in the interpreter:
>(square 4)
>16


Now lets try and define a procedure to find larger number from the two given numbers:

(define (findMax x y) (cond (( > x y) x) (else y)))

cond is for condition, and in front of the condition we are placing the conditions and if it evaluates to true then we simply give the output we desire for that condition and at the end if none of the preceding condition evaluates to true then we return the desired output for that scenario by placing an else before the output.

Similarly we can define another procedure which finds the minimum of the two numbers:
(define (findMin x y)(cond ((< x y)x)(else y)))

Now let us define another procedure which takes in 3 inputs and returns the summation of square of two large numbers:

(define (largeSquareSum x y z)(cond((and (> x y) (> z y)) (+ (square x) (square z)))((and (> y x) (> z x)) (+ (square y) (square z)))((and (> x z) (> y z)) (+ (square x) (square y)))))

The same program can be written in a more neat way as follows:

(define (largeSquareSum x y z)(cond((and (> x y) (> z y)) (+ (square x) (square z)))
                                                              ((and (> y x) (> z x)) (+ (square y) (square z)))
                                                              ((and (> x z) (> y z)) (+ (square x) (square y)))))

The above program follows a very simple logic, it checks if x,z pair are larger than y, or if y,z pair are larger than x or if x,y pair is larger than z and returns the sum of square of the pairs whichever is larger.

If we pass the following to the interpreter we will get :
>(largeSquareSum 1 2 3)
>13

Written By,
Sarvesh Bhatnagar

No comments:

Post a Comment