In: Computer Science
Write a simple Calculator program using Scheme programming language. It should be able to do following operations: "+", "-", " * *, "/". the format when using the calculator function should be (calculator(operand1 operation operand2)) -> (calculator(2 + 5)) should give the output of 7.
Code:
;;(car List) returns first element of list i.e, operand1
;;(cadr List) returns second element of list i.e, operation
;;(caddr List) returns third element of list i.e, operand2
(define (calculator List) ;;Takes list as input which is of form
(operand1 operation operand2)
(cond ((equal? '+ (cadr List)) (add (car List) (caddr List))) ;;If
(cadr List) i.e, if second element of list is "+" then add 1st and
3rd operands
((equal? '- (cadr List)) (sub (car List) (caddr List))) ;;If (cadr
List) i.e, if second element of list is "-" then subract 1st and
3rd operands
((equal? '* (cadr List)) (mul (car List) (caddr List))) ;;If (cadr
List) i.e, if second element of list is "*" then add multiply and
3rd operands
((equal? '/ (cadr List)) (div (car List) (caddr List))) ;;If (cadr
List) i.e, if second element of list is "/" then divide 1st and 3rd
operands
(else 'not-valid-operation)))
(define (add a b) ;;Returns sum of two operands
(cond ((= a 0) b) ;;if b = 0 returns value of a
((= b 0) a) ;;if a = 0 returns value of b
(else (+ a b)))) ;;else add two operands
(define (sub a b) ;;Returns subraction of two operands
(cond ((= b 0) a) ;;if b = 0 returns value of a
(else (- a b)))) ;;else subract two operands
(define (mul a b) ;;Returns multiplication of two operands
(cond ((= a 0) 0) ;;if a = 0 returns 0
((= b 0) 0) ;;if b = 0 returns 0
(else (* a b)))) ;;else multiply two operands
(define (div a b) ;;Returns division of two operands
(cond ((= a 0) 0) ;;if a = 0 returns 0
((= b 0) 'infinity) ;;if b = 0 returns 'infinity
(else (/ a b)))) ;;else divide two operands
Snapshot of Code and Output: