On Tue, Feb 11, 2025 at 11:25 PM Alexander Burger <picolisp@software-lab.de> wrote:
> > 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. > > Thanks! > (de fiboSwap (N) > (let (A 0 B 1) > (do N > (swap 'B (+ (swap 'A B) B)) ) ) ) > > That is really cool! Something to keep in mind. I took a moment to rewrite the tco versions of the swap, mtf, mft functions I had using my newly realized understanding of nth, con, conc, insert.... (code below). Shorter, simpler, and much! faster on large lists. : (swappXchg (1 . 7) (1 2 3 4 5 6 7 8 9)) # Swap -> (7 2 3 4 5 6 1 8 9) : (mtfConc (1 2 3 4 5 6 7 8 9) 7) # Move to front -> (7 1 2 3 4 5 6 8 9) : (mftConc (1 2 3 4 5 6 7 8 9) 7) # Move from top -> (2 3 4 5 6 7 1 8 9) /Lindsay # Swap two elements in a list (de swappXchg (P L) (when (and (pair P) (lst? L)) (ifn (> (cdr P) (car P)) (setq P (cons (cdr P) (car P))) ) (let (Lst L Lhs (car P) Rhs (cdr P) LhsN (nth L Lhs) RhsN (nth LhsN (inc (- Rhs Lhs))) ) (when (and LhsN RhsN) (xchg LhsN RhsN)) L ) ) ) # Move from top (de mftConc (X N) (cond ((and (> N 1) (lst? X)) (let (Elt (cons (car X)) Lhs (head (dec N) (cdr X)) Rhs (cdr (nth X N)) ) (con Elt Rhs) (conc Lhs Elt) Lhs ) ) (T X) ) ) (de mftInsert (X N) (cond ((and (> N 1) (lst? X)) (insert N (cdr X) (car X))) (T X))) # Move to Front (de mtfConc (X N) (cond ((and (> N 1) (lst? X)) (let (Lhs (head (dec N) X) Rhs (cdr (nth X (dec N))) Elt (cons (car Rhs)) ) (ifn Rhs X (con Elt Lhs) (conc Elt (cdr Rhs)) Elt ) ) ) (T X) ) )