Created
October 31, 2014 10:56
-
-
Save txus/fc5e0fde1fc08ba85ce1 to your computer and use it in GitHub Desktop.
Haskell-like function composition in Ruby - let the mad horses unleash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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