Reputation: 12363
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.
Upvotes: 1
Views: 995
Reputation: 40688
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.
Upvotes: 3