Skip to content

Instantly share code, notes, and snippets.

@armstnp
Created June 4, 2022 21:57
Show Gist options
  • Save armstnp/bb2a88bcb053d2195f42c60a0cf15a65 to your computer and use it in GitHub Desktop.
Save armstnp/bb2a88bcb053d2195f42c60a0cf15a65 to your computer and use it in GitHub Desktop.

Further Lisp compression tinkering. Basic idea: most languages optimize for sequence structure, which fits for procedural code:

Statement A modifies the environment
Statement B modifies the environment
Statement C uses the modified environment to produce value
...

But a more functional style tends to structure things as a nested recursive tree, with the right-most branch being the heaviest.

Let the environment be modified by A in...
   Let the environment be modified by B in...
     this value C using that modified environment

Sooo if you instead say 'the default syntax favors the recursive structure, and sequence must be explicit', you can take lispy code like this:

(define (read-points input)
  (define (read-point line)
    (let ((coords (map string->number (string-split line ","))))
      (cons (car coords) (cadr coords))))
  (list->set
    (let loop ((input (string-split input "\n"))
               (points '()))
      (if (null? input)
        points
        (let ((line (car input)))
          (unless (non-empty-string? line)
            points
            (loop
              (cdr input)
              (cons (read-point line) points))))))))

... and turn it into something like this...

define: read-points input

• define: read-point line
  let coords: map string->number: string-split line ","
  cons (car coords): cadr coords

• list->set

  let loop
  • input: string-split input "\n"
  • points '()
  
  if (null? input) points

  let line: car input
  unless (non-empty-string? line) points

  loop
  • cdr input
  • cons (read-point line) points

.... where bullets indicate siblings, or sequential children of the parent node; and all other statements at the same level are nested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment