Skip to content

Instantly share code, notes, and snippets.

@delonnewman
Last active November 18, 2015 20:29
Show Gist options
  • Save delonnewman/ecd096ad8ecafbf1471c to your computer and use it in GitHub Desktop.
Save delonnewman/ecd096ad8ecafbf1471c to your computer and use it in GitHub Desktop.
fun.rb - functional Ruby, taking some ideas from Clojure
class Hash
def to_proc
lambda { |x| self[x] }
end
end
class Array
def to_proc
lambda { |x| self[x] }
end
end
def get(key)
lambda { |x| x[key] }
end
def fib(n)
@fibs ||= {}
if @fibs[n] then @fibs[n]
else
f = if n < 0 then raise "n must be greater or equal to 0"
elsif n <= 1 then n
else
fib(n - 2) + fib(n - 1)
end
@fibs[n] = f
f
end
end
fibs = (0..10).map(&method(:fib))
p [0, 8, 5, 2].map(&fibs)
p [{a: 1, b: 2}].map(&get(:a))
p [:a, :b].map(&{a: 1, b: 2})
p [0, 1, 2, 3, 4].map(&[:a, :b, :c, :d, :e])
def test(&blk)
blk.call(0)
end
p test(&[:a, :b])
# Method / Proc combinitors
# =========================
#
# `chain`
# -------
#
# [].method(:last).then(:nil?)
#
# [].method(:last) << &:nil
#
# [].map(&(&:last << &:nil?))
#
# equivalent to
#
# [].last.nil?
#
# [].map { |x| x.last.nil? }
#
#
# `compose`
# =========
#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment