Skip to content

Instantly share code, notes, and snippets.

@txus
Created October 31, 2014 10:56
Show Gist options
  • Save txus/fc5e0fde1fc08ba85ce1 to your computer and use it in GitHub Desktop.
Save txus/fc5e0fde1fc08ba85ce1 to your computer and use it in GitHub Desktop.
Haskell-like function composition in Ruby - let the mad horses unleash
require 'blankslate'
class Proc
def self.comp(f, g)
lambda { |*args| f[g[*args]] }
end
def *(g)
Proc.comp(self, g)
end
end
module Kleisli
class ComposedFn < BlankSlate
def initialize(fns=[])
@fns = fns
end
def method_missing(m, *args, &block)
fn = -> a, x { x.send(m, *a) }.curry[args]
ComposedFn.new(@fns + [fn])
end
def call(*args)
@fns.reduce(:*).call(*args)
end
end
end
_ = Kleisli::ComposedFn.new
# BE MAD
fn = _ . first . last
puts fn.call([[1,2],[3,4]]) # => 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment