Skip to content

Instantly share code, notes, and snippets.

@plonk
Forked from ha2ne2/pipe.rb
Last active August 29, 2015 14:12
Show Gist options
  • Save plonk/463cdf49cc94ff6b07e1 to your computer and use it in GitHub Desktop.
Save plonk/463cdf49cc94ff6b07e1 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)
if pipe[1].kind_of?(Proc)
pipe[1] = pipe[1].()
else
pipe[1]
end
end
def butlast(ary)
ary[0..-2]
end
def pipe_to_array(pipe)
butlast pipe.flatten
end
def iterate(f, x)
[x, -> { iterate f, f.(x) }]
end
def take(count, pipe)
if pipe.nil? or count == 0
nil
else
[head(pipe), take(count - 1, tail(pipe))]
end
end
def filter(f, pipe)
if f.(head(pipe))
[head(pipe), -> { filter f, tail(pipe) }]
else
filter(f, tail(pipe))
end
end
def primes(n)
sieve = ->(pipe){
[
head(pipe),
-> {
sieve.(filter(-> x { x % head(pipe) != 0 },
tail(pipe)))
}
]
}
pipe_to_array take(n, sieve.(iterate(:succ.to_proc, 2)))
end
def nats(n = 1)
[n, -> { nats(n + 1) }]
end
p primes 10
# => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
p pipe_to_array(take(10, nats))
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment