On Tue, Feb 11, 2025 at 02:41:01PM -0800, Lindsay Lawrence wrote: > > I usually approach such tasks with loops, with a rather > > different mental model. > > > That is interesting! Can you say more about your mental model? > I am often surprised by how often I end up with recursive solutions when > hacking on a particular problem in picolisp.
If a problem is a linear operation, like traversing a list, a loop is more natural for me. For traversing a tree, recursion is better of course. One of the first examples in SICP is (de sqrt-iter (Guess X) (if (good-enough? Guess X) Guess (sqrt-iter (improve Guess X) X) ) ) I would never get the idea to write it that way. Instead, I would (de sqrt-iter (Guess X) (until (good-enough? Guess X) (setq Guess (improve Guess X)) ) Guess ) > Concerning swap, we could for completeness mention that there is also > > the built-in 'xchg' function: > > > > : (let L (1 2 3 4 5 6 7) > > (xchg (nth L 3) (nth L 5)) > > L ) > > -> (1 2 5 4 3 6 7) > > > > The swap function I implemented was an exercise after working with some > particularly large lists. Yes, I thought so. > > I did find after writing that code that there is xchg as well as a few > other useful functions in this vein in picolisp...'insert' and even 'swap'! Yeah. 'swap' is btw useful to make an iterative version of our good old fibo function. Instead of (de fibo (N) (if (>= 2 N) 1 (+ (fibo (dec N)) (fibo (- N 2))) ) ) or (de fiboTco (N) (let (A 0 B 1) (tco (N A B) (if (=0 N) A (tc (dec N) B (+ A B)) ) ) ) ) we can write (de fiboSwap (N) (let (A 0 B 1) (do N (swap 'B (+ (swap 'A B) B)) ) ) ) :) > I sometimes don't realize (at first) when a particular function returns a > 'pointer' into a list, vs a 'value'. I see, these are valid terms. The reference calls such a 'pointer' a 'var'. > A slight change to your little function achieves the single pass > performance...in far less code than the function I shared! > > : (let (L (1 2 3 4 5 6 7 8 9) > lhs (nth L 3) > rhs (nth lhs (inc (- 5 3)))) > (xchg lhs rhs) L) > -> (1 2 5 4 3 6 7 8 9) Indeed, this is better for very long lists, as the second traversal is shorter. Note, however, that for shorter lists (less than perhaps a hundred cells), it is in fact slower because of the overhead for the additonal variable bindings and the function calls 'inc' and '-'. ☺/ A!ex -- UNSUBSCRIBE: mailto:picolisp@software-lab.de?subject=Unsubscribe