Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Created June 14, 2012 14:56
Show Gist options
  • Save jackrusher/2930841 to your computer and use it in GitHub Desktop.
Save jackrusher/2930841 to your computer and use it in GitHub Desktop.
Naive functional composition in Ruby
# Loads a directory's of files, each containing an eponymous function,
# in lexical order, then composes a function the calling of which will
# apply entire chain.
def compose(funcs)
funcs.map! { |f| f.to_proc }
if funcs.length == 2
# simple two function composition
lambda { |*args| funcs[0].call(funcs[1].call(*args)) }
elsif funcs.length > 2
# recursively compose:
compose(funcs.shift, compose(*funcs))
else
lambda { nil }
end
end
def compose_from_dir(directory)
steps = Dir.glob("#{directory}/*.rb")
steps.reverse!.map! do |step|
load step
method(step.gsub(/^.*\/\d\d\d_/,"").gsub(".rb","").to_sym)
end
if steps.size > 1
compose(steps)
else
steps[0]
end
end
transform = compose_from_dir("Steps")
puts transform.call("articles")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment