Skip to content

Instantly share code, notes, and snippets.

@ha2ne2
Last active August 29, 2015 14:11
Show Gist options
  • Save ha2ne2/6c8656a0e439b296a9c5 to your computer and use it in GitHub Desktop.
Save ha2ne2/6c8656a0e439b296a9c5 to your computer and use it in GitHub Desktop.
## PIPE BY PAIP ON MATZ LISP
## 2014-12-23
# (primes 10)
# => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
(def make_pipe(head,tail) [head,tail] end)
(def head(pipe) pipe[0] end)
(def tail(pipe) pipe[1].kind_of?(Proc) ? pipe[1] = pipe[1].call : pipe[1] end)
(def butlast(ary) (ary.first ary.size-1) end)
(def my_succ(n) n+1 end)
(def pipe_to_array(pipe) (butlast pipe.flatten) end)
(def iterate(f,x) [x, ->{iterate f, (f.call x)}] end)
(def take(count, pipe, result: pipe)
((pipe == nil) or (count == 1)) ?
result :
(take count-1, (tail pipe), result: result) end)
(def filter(f, pipe)
(f. (head pipe)) ?
[(head pipe), ->{filter f, (tail pipe)}] :
(filter f, (tail pipe)) end)
(def primes(n)
sieve = ->(pipe){[(head pipe),
->{sieve. (filter lambda{|x| x % (head pipe) != 0}, (tail pipe))}]}
(pipe_to_array (take n, (sieve. (iterate (method :my_succ), 2)))) end)
(primes 10)
#=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment