Sunday, April 23, 2006

LISP!

Hmmm. So here is my first functional lisp!

This is also the first time I tried to reverse the digits of an integer (with digits interpretted in a given base) using recursion. I am not very sure if I cannot unpack the multiple returns into individual variables - like in python. That would be very cool!

I am also pretty sure the lisp I have written is not very idiomatic ... but writing tons of code alone can instill the idioms in the code-thought channels of the brain. In fact, I tend to think that one does not think in the usual sense of the term while writing programs - it seems to be more of a subconscious activity. But that can hapen only after a language ingrains itself deeply in one's brain. Till then its very consciously code and hence code that is not very beautiful - its code that looks contrieved to the initiated.


(defun pow(n i)
(let ((p 1))
(dotimes (i i) (setf p (* p n)))
p))


(defun rev(n base)
(let ((worker (lambda (n base self)
(if (= 0 n)
(list 0 0)
(let ((temp (funcall self (floor (/ n base)) base self)))
(list
(+ (* (mod n base) (pow base (second temp))) (first temp))
(1+ (second temp))))))))
(first (funcall worker n base worker))))


(rev 1357924680 10)

(rev #b1111011101101 2)


LISP

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home