Monday 6 February 2017

MultiThreaded Calculator in Lisp

Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp.

Before we get to the Implementation of the Program, get your Lisp Programing Environment Setup. In case you haven't yet set it up , here's an article about the same.

Implementation


We have created a text based interface for the calculator which accepts two numbers. The result of addition , subtraction , multiplication and division in calculated.

Input: Accepted in binary
Output: Displayed in binary

Functions
4 Lamda Function to compute each of the operations
btd: This function is for binary to decimal. Converts a binary to decimal


Code




Calculator program using multiple threads

(defvar multi)  ;store the multliplier
(defvar ans)    ;store the answer to return
(defvar bito)   ;store a single bit 1 or 0

(defun btd (n1 );function to convert binary to decimal
   
   (setq ans 0 )  
   (setq multi 1)   
   (loop 
      (setq bito(mod n1 2))
      (setq ans(+ ans (* bito multi )))
      (setq multi( * multi 2))
      (setq n1(floor n1 10))
      (when (eql n1 0) (return-from btd ans))
   )
   
   
   
   
)


(defvar num1)
(defvar num2)
(write-line "Enter number1")
(setq num1 (read))
(write-line "Enter number2")
(setq num2 (read))

(write-line "You entered numbers")
(setq num1 (btd num1))
(setq num2 (btd num2))
(format t "num1= ~b , num2= ~b " num1 num2)




(sb-thread:make-thread
  (lambda ()
    (progn
      (sleep 0)
      (format t "~%The addition is ~b" (+ num1 num2))
      )))

(sb-thread:make-thread
  (lambda ()
    (progn
      (sleep 0)
      (format t "~%The subtraction is ~b" (- num1 num2))
      )))


(sb-thread:make-thread
  (lambda ()
    (progn
      (sleep 0)
      (format t "~%The multiplication is ~b" (* num1 num2))
      )))

(sb-thread:make-thread
  (lambda ()
    (progn
      (sleep 0)
      (format t "~%The division is ~b~%" (/ num1 num2))
      )))

Output


student@localhost:~$ sh sbcl.run as1.lisp
Enter number1
101
Enter number2
111
You entered numbers
num1= 101 , num2= 111
The addition is 1100
The subtraction is -10
The multiplication is 100011
The division is 101/111


Note: In case, you are wondering hot to run this program. Particularly the sbcl.run command.
Actually its a script file which was written in the working directory. I personally like this way of getting the job done as its faster than firing sbcl, the load and running it.
The execution is explained here:Running a Lisp Program


No comments:

Post a Comment