1

I am to write a lisp program to produce the actual value of a hexadecimal number. I have written a function but seem to be getting a stackoverflow (deep) error. I was wondering if anyone could point out my mistake or guide me in the right direction.

I would appreciate it if no code was posted for this question as this is part of a homework assignment. Hence I would only like an explanation or direction where I might be going wrong.

I feel my problem is that my recursion is not terminating but I don't know how to fix it.

Here's my code:

(defun calc (hex)
  (if hex
    (if (> (length hex) 1)
     ( + (first (reverse hex)) (* 16 (calc (reverse hex)))) hex))) 

Thanks in advance.

3
  • Just to clarify, what is the type of input? Is it a number or a string or something else? And I assume the output is supposed to be the same number, but in base 10 correct? Commented Mar 4, 2013 at 1:53
  • The number is a list of type '(7 d d) sort of an exploded list of hex digits Commented Mar 4, 2013 at 3:51
  • And the output is supposed to be a base 10 number. Commented Mar 4, 2013 at 4:00

1 Answer 1

3

The "base case" (the case/state where recursion actually stops) is that hex has length of one or less. Tell me, each time you call calc again, is the input to calc ever getting smaller? if not, then it's mathematically impossible for the input to ever reach the base case.

Let's say hex starts with length 9. When you call calc again, you have reversed hex. So now hex is reversed, but it still has a length of 9. I suspect that is why the recursion never stops.

Sign up to request clarification or add additional context in comments.

3 Comments

omg no its not thanks I think that's the problem. I meant to call (rest (reverse hex)) instead of just (reverse hex)
I had one last question. Would you happen to know how I might be able to convert an item like the character d into its decimal form 13 without using the parse-integer function? I read that lisp uses ~x but that doesn't seem to work for me for some reason.
Btw if anyone is wondering how I finally got over the hex representation problem,I was told to use the COND function which is the lisp equivalent of a switch-case in java. Pretty ugly and hard coded but it got the job done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.