Created
September 6, 2013 09:37
-
-
Save qbyt/6461641 to your computer and use it in GitHub Desktop.
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
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