I received a Lisp book for Christmas from mom (and no she does not have a PhD but knows how to find wishlists and sort by price). I am going through it now and I found a function definition that is endlessly amusing me as a Python developer. I am hoping to bring you the same warm fuzzies momentarily.
Imagine we have a name, “Mr Rick Sanchez”. We would like a function to return the first name of this name, “Rick”.
Usually what I might do is to split the string and get the second argument; then handle edge cases like the empty string yadda yadda. Then discover “Dr Mr Rick Sanchez”, another special case, and then get smart and
while current in TITLES iterate over my string to find the first name.
All this is fine and it would work after 10 minutes, 2 syntax errors and 3 utterances of sh!t. But also look at this lisp implementation:
(defun first-name (name) (if (member (first name) *titles*) (first-name (rest name)) (first name)))
I mean it is recursive and has cute functions like
rest, but I think what I like most about it, is that it doubled down on the simple first-word-of-the-string approach with a smart maneuver and did not add more complexity by more loops and
current variables and edge cases. This is probably partially Lisp and partially Peter Norvig; nonetheless it is very amusing.
Still here? see me convert it to Python
I tried writing exactly that in Python: a function of 3 lines beautiful as poetry. And here it is:
def first_name(name): if first(name) in TITLES: return first_name(rest(name)) return first(name)
and here is all the duct tape that assisted us in accomplishing this ideal, thank you:
def noner(func): def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except: return None return wrapped @noner def first(string): return string.split() @noner def rest(string): return ' '.join(string.split()[1:])