Question:
Recursive Decimal to Binary function in Common Lisp?
John P
2011-10-12 22:18:12 UTC
(defun binaryize (N)
(cond
((not (numberp N)) nil) ;;;Handles Input
((not (plusp N)) nil) ;;;Handles Input
((zerop N) 0)
( t (cons (binaryize (/ N 2)) (mod N 2)))))

This is what I came up with and I can't figure out why it's not working, I'm very new to lisp and I just wrote it out like I would in C++. Any help would be greatly appreciated.
Four answers:
Misesean X
2011-10-16 21:46:13 UTC
I really don't think you wrote it "like you would in C++". You probably should.



You have a problem with the way you build up the result list: the result will look like (...((((NIL . 1) . 0) . 0) . 1) ...); you probably wanted (1 0 0 1 ...) -- if you really wanted a list at all. Try something like



(defun binaryize-1 (N r)

(if (zerop N)

r

(multiple-value-bind (a b) (floor N 2)

(binaryize-1 a (cons b r)))))



(defun binaryize (N)

(if (and (numberp N) (plusp N))

(binaryize-1 N '())

(if (eql N 0) '(0) nil)))



========



Correcting a couple of things in the previous reply: (/ N 2) will make rational numbers 1/2, 1/4, etc., not 0.5, 0.25, etc.; (floor (/ N 2)) is better written (floor N 2), though FLOOR returns two values, so (multiple-value-bind (a b) (floor N 2) (cons (binaryize a) b)) would be better (but see above); and Common Lisp's returning of correct answers has nothing do with the being "dynamically typed".
ratter_of_the_shire
2011-10-13 13:43:21 UTC
here's the thing I see



(binaryize (/ N 2))



say N is 1, it will pass 0.5 to binaryize in the last satement, then 0.25, then 0.125 ... and you're probably bumping into a recurcion depth exceeded error.



try instead



(cons (binaryize (floor (/ N 2))) (mod N 2))



Learn how to use the trace function for your implementation/interperter, which should show you how the function is being called, and would have showed you the mistake very quickly.



C++ will truncate or floor the number so long as the variable is in the int type.



Common Lisp is dynamically typed so will convert integers to floats and then bignums as necessary to preserve precision, unless you tell it to round.



there may also be integer implementation of / in some implementations of common lisp that you could use as well
2016-12-08 17:39:00 UTC
Numberp Lisp
segundo
2016-12-07 08:53:01 UTC
you could wreck it down so as that your ordinary procedures the utmost maximum set bit and calls itself on each and every of the bits below it. That way it may fulfill the 'recursive' requirement.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...