Skip to content

Instantly share code, notes, and snippets.

@fronx
Created September 1, 2011 00:36
Show Gist options
  • Save fronx/1185131 to your computer and use it in GitHub Desktop.
Save fronx/1185131 to your computer and use it in GitHub Desktop.
# https://gist.github.com/1185131
class Array
def next; self[1..-1] end
# returns a function that is the combination of a sequence of function calls
# on some external arguments. the functions combined are the elements of self.
def compose
lambda do |*args|
inject(*args) do |mem, fn|
fn.call(mem)
end
end
end
def to_proc
map(&:to_proc).compose
end
end
class Hash
def to_proc
map { |k, v| lambda { |x| x.send(k, *[*v]) } }.
compose
end
end
class Object
def out; tap { |x| puts x.inspect } end
end
[:reverse, :next].to_proc.call([1,2,3,4]).
out # => [3,2,1]
### Traverse some tree-like thing ###
tree =
[
[0], # 0
[ # 1
[1], # 0
[ # 1
2, # 0
[3,4,5]] # 1
]]
[{:[] => 1}, {:[] => 1}, :last, {:[] => [1,2]}].to_proc.call(tree).
out # => [4,5]
def path(*indices)
indices.map { |i| Symbol === i ? i : {:[] => i} }.to_proc
end
path(1,1,:last,[0,2]).call(tree).
out # => [3,4]
### One pass, multiple transformations ###
%w[ ab bc ].map(&[ :upcase, :reverse, {:gsub => [/B/, "x" ]} ]).
out # => ["xA", "Cx"]
%w[ ocd aEd ab ].map(&[ :upcase, :chars, :sort, :join ]).sort.
out # => ["AB", "ADE", "CDO"]
# ruby-equivalent of clojure's partial
[1,2,3].map( &{:* => 2} ).
out # => [2,4,6]
def partial(procable); procable.to_proc end
double = partial(:* => 2)
[1,2,3].map(&double).
out # => [2,4,6]
# compose partials
[1,2,3,4,5,6,7,8].map(&[ {:* => 3}, {:% => 4} ]).
out # => [3, 2, 1, 0, 3, 2, 1, 0]
[3,7,2,1,4,9,12].select(&[ {:% => 3}, {:== => 0} ]).
out # => [3, 9, 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment