Emacs Lisp

In yesterday’s dgplug session, we were taught the Emacs Lisp programming, something very new for me which I had never done before. I liked the way the code is written because of its simplicity and normal English language but the way in which parenthesis are put is little confusing. That can be actually done by practicing writing code in Emacs Lisp. I was given a link to a video in the session by the mentor which i found really helping. I summarized all the codes with comments we learned in the session. You can have a look for them here .

After the session we also got some work to do – We have to select a problem from the Project Euler  and implement the solution in Emacs Lisp. So I selected the very first problem that is –

Find the sum of all the multiples of 3 or 5 below 1000.

I first wrote the code in python –

sum = 0                           #assigned sum variable as 0
for i in range(0, 1000):          #used range function to iterate from 0,1000 in the for loop
if(i % 3 == 0) or (i % 5 == 0):   #checked the condition
sum += i                          #if true then add with sum 
print (sum)                       #print total sum

Output ->

 233168 

I tried to proceed in the same way for Emacs Lisp programming and i got the output in two ways once defining a function and one without function.

1) Defining the function sum

(defun sum (list)
  (apply '+ (mapcar
	     '(lambda (x) (if (or (eql (% x 3) 0) (eql (% x 5) 0))
			      x 0) )
	     list) ))
(sum (number-sequence 1 999) ) 

Output ->

 233168 (#o707320, #x38ed0, ? ) 

In the first line I defined the function sum with parameter list then I wrote a condition to check and add all the numbers satisfying the condition to give the total. To give the range I used the number-sequence function.

2) Without using function and using loop (do)

 (let ((sum 0))
  (cl-loop for x from 1 to 999
	   do (if (or (zerop(mod x 3 )) (zerop(mod x 5 )))
		  (setq sum (+ x sum))))
 sum)  

Output->

 233168 

Used the same logic but mentioned the range in the loop which is more problem statement oriented result.

I really liked the Euler’s problem statements will try to practice more from them each day.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s