Why Nostr? What is Njump?
2023-05-12 03:11:04

hazlin on Nostr: So, I've been reading in "On Lisp", and there has been a lot I didn't expect, like a ...

So, I've been reading in "On Lisp", and there has been a lot I didn't expect, like a focus on writing the most performant code.

One of the proposed utility functions seems to be a faulty concept.

It says don't use "(> (length x) (length y))" to determine which list is longer, instead compare the lists incrementally with recursion so length doesn't have to reach the end of both lists.

01 (defun simple-longer (x y)
02 (> (length x) (length y)))

CL-USER> (simple-longer '(1 2 3) '(1 2 3 4))
NIL
CL-USER> (simple-longer '(1 2 3 4 5) '(1 2 3 4))
T

The proposed code is
01 (defun OnLisp-longer (x y)
02 (labels ((compare (x y)
03 (and (consp x)
04 (or (null y)
05 (compare (rest x) (rest y))))))
06 (if (and (listp x) (listp y))
07 (compare x y)
08 (> (length x) (length y)))))

CL-USER> (onlisp-longer '(1 2 3) '(1 2 3 4))
NIL
CL-USER> (onlisp-longer '(1 2 3 4 5) '(1 2 3 4))
T

BUT! Unless I've seen wrong, line 08 of OnLisp-longer undoes any saved work, and traverses the remainder of either x or y. This proposed more efficient utility function, does more work overall.
Author Public Key
npub1n69rack0mfdppstvru3ssngswvrzqyz3qzplqth4256rqzg0pf3s9gm0cc