First off let me just say I know what I'm doing is not ideal, but I'm trying to write the member? function from The Little Schemer using Hy.
(setv else True)
(defn null? [lst]
" If list is empty return True else False "
(if lst
False
True))
(defn member? [a lat]
" Checks if value is a member of a list "
(cond
[(null? lat) False]
[else (or (= (first lat) a)
(member? a (rest lat)))]))
(print (member? 1 '(2 3 4 1)))
This works exactly how I expect. The problem is, if the list is greater than 4 elements long I get the error
RecursionError: maximum recursion depth exceeded while calling a Python object
I know Python isn't meant to do recursion and in the Python docs it even says that there is a default recursion limit to keep the C stack from overflowing. On my machine getrecursionlimit()
yields the value of 1000, and I was able to successfully set it to over 20,000 before getting a segfault. Even with it set to 20,000 I am still getting the error on a list of 5 elements. What I don't understand is... How am I hitting over 20,000 levels of recursion on a 5 element list?
And for those curious I'm using Python 3.6.5, MacOS Mojave version 10.14.6 on a 15" Macbook pro, Hylang version 0.18.0, and the output of my program using hy2py is
from hy.core.language import first, rest
from hy import HyExpression, HyInteger
hyx_else = True
def is_null(lst):
""" If list is empty return True else False """
return False if lst else True
def is_member(a, lat):
""" Checks if value is a member of a list """
return False if is_null(lat) else first(lat) == a or is_member(a, rest(lat)
) if hyx_else else None
print(is_member(1, HyExpression([] + [HyInteger(2)] + [HyInteger(3)] + [
HyInteger(4)] + [HyInteger(5)] + [HyInteger(1)])))