Advertisement
Guest User

un-accum-and-reverse

a guest
Jul 18th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.26 KB | None | 0 0
  1. ;;https://stackoverflow.com/questions/62946821/
  2. ;;scheme-is-it-possible-to-convert-a-list-of-s-expressions-
  3. ;;into-a-list-of-atoms/62959036#62959036
  4.  
  5. ;;by https://stackoverflow.com/users/5920214/tfb,
  6. ;;tweaked by https://stackoverflow.com/users/849891/will-ness,
  7. ;;removing the tailrec-accum-and-reverse
  8. (define (tree->atoms tree)
  9.   (define (atom? x) (not (pair? x)))
  10.   (let tree->atoms-loop ([it tree]
  11.                          [agenda '()])
  12.     (cond [(null? it)
  13.            ;; no more left
  14.            (if (null? agenda)
  15.                ;; no more agenda: we're done
  16.                '()
  17.                ;; more agenda, so carry on
  18.                (tree->atoms-loop (first agenda)
  19.                                  (rest agenda)))]
  20.           [(atom? it)
  21.            ;; we've found an atom which is not ()
  22.            (if (null? agenda)
  23.                ;; no more agenda: we're done
  24.                (list it)
  25.                ;; more agenda, so carry on
  26.                (cons it (tree->atoms-loop (first agenda)
  27.                                           (rest agenda))))]
  28.           [else ; (not (atom? it))
  29.            ;; cons: look at the car, and stuff the cdr onto the agenda
  30.            (tree->atoms-loop (car it)
  31.                              (cons (cdr it) agenda))])))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement