Thursday, 29 November 2018

Arithmetic Operations - Lisp

Arithmetic Operations - Lisp


Any operation in lisp follows a prefix notation. i.e. Operator is placed before the operand's.
e.g. 
Addition: 
>(+ 4  5)
>9

The above operation is evaluated as 4 + 5

Subtraction:
>(- 10 4)
>6

The above operation is evaluated as 10 - 4

Division:
>(/ 20 10)
>2

The above operation is evaluated as 20 / 10

Multiplication:
>(* 2 3)
>6

The above operation is evaluated as 2 * 3


Similarly if we want to perform some complex nested operations such as ((2+4)*(5-2)) / (10 + 2) * 4

The same can be done as making an operation tree as:

                   /

      *                     *  

  +      -             +       4

2   4  5   2    10    2


Hence by looking at the nested tree, we know that in total division appears first, then we divide up the operations into two parts further we know in those two parts multiplication is needed to be performed between 2+4 & 5-2 and multiplication between 10 + 2 and 4 ... so our prefix notation leads to the following steps.

1.(/ (*)(*))
2.(/ (*(+)(-))(*(+) 4))
3.(/ (* (+ 2 4) (- 5 2)) (* (+ 10 2) 4))

Giving the equation obtained in 3 to the interpreter:
>(/ (* (+ 2 4) (- 5 2)) (* (+ 10 2) 4))
>3/8

hence the result of the operation is 3/8.

Written By, 
Sarvesh Bhatnagar

No comments:

Post a Comment