Skip to content

Instantly share code, notes, and snippets.

@qbyt
Created September 6, 2013 09:37
Show Gist options
  • Save qbyt/6461641 to your computer and use it in GitHub Desktop.
Save qbyt/6461641 to your computer and use it in GitHub Desktop.
class Proc
def self.compose(f, g)
lambda { |*args| f[g[*args]] }
end
def *(g)
Proc.compose(self, g)
end
end
def comprehension(range, mappers = [], filters = [])
mappers = mappers.reduce(:*)
filters = filters
filtered = range.reduce([]) do |accum, val|
inc = filters.map do |filter|
filter[val]
end.all?
inc ? accum << val : accum
end
filtered.map { |x| mappers[x] }
end
# list comprehension
comprehension(1..10, [->(x) { x / 2 }, ->(y) { y ** y }], [->(z) { z.odd? }])
# set comprehension
Set.new(comprehension(1..10, [->(x) { x / 2 }, ->(y) { y ** y }], [->(z) { z.odd? }]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment