Binary operations in Lisp

Discussion of Common Lisp
Post Reply
rhjadhav
Posts: 1
Joined: Wed Nov 12, 2014 3:06 am

Binary operations in Lisp

Post by rhjadhav » Wed Nov 12, 2014 3:15 am

hello everyone. i am new to Lisp. i dont know how to perform binary operations in LISP?
can anyone share sample of code for binary addition or multiplication plz

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: Binary operations in Lisp

Post by Goheeca » Sat Nov 15, 2014 2:54 am

A binary operation is treated as any other n-ary operation. There is nothing special about it. Use prefix notation:

Code: Select all

(+ 1 2) ; = 3
(* 2 3) ; = 6
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

sylwester
Posts: 133
Joined: Mon Jul 11, 2011 2:53 pm

Re: Binary operations in Lisp

Post by sylwester » Fri Nov 28, 2014 4:31 pm

Integers don't have base when they are stored. Your reader can read numbers in several different bases.

Code: Select all

(+ 10 #xa #b1010) ; ==> 30 
Now when makeing a string out of the number you get to choose the base:

Code: Select all

(let ((thirty (+ 10 #xa #b1010)))
  (format nil "~n ~x ~o ~b" thirty thirty thirty thirty))
; ==> "30 1E 36 11110"
There you have it. 30 displayed in 4 different bases. In CL you have the special variable *print-base* which sets the default base in which numbers are printed and *read-base* which sets the default base in which numbers are read when parsed:

Code: Select all

(let ((*print-base* 16)
        (*read-base* 2))
  (princ (read-from-string "1011"))) ; ==> B
Thats about all there is to know about displaying and parsing numbers. Now all your base are belong to you :-)
I'm the author of two useless languages that uses BF as target machine.
Currently I'm planning a Scheme compiler :p

edgar-rft
Posts: 226
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany

Re: Binary operations in Lisp

Post by edgar-rft » Tue Dec 02, 2014 6:09 am

I think the question was about binary operations (operations that take exactly two arguments), not how to compute numbers represented in binary format. And the question smells very much like homework...

Post Reply