Skip to content

Instantly share code, notes, and snippets.

@txus txus/wtf.rb
Created Oct 31, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.