Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active July 14, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/83e2d70d54d45bbcdf6e1a357982c345 to your computer and use it in GitHub Desktop.
Save baweaver/83e2d70d54d45bbcdf6e1a357982c345 to your computer and use it in GitHub Desktop.
# Do note that I'm being purposely verbose to make this easier to read through,
# as transducers are already a bit hard to grok without shorthanding things.
def maps(&function)
proc { |accumulator, value|
accumulator << function.call(value)
}
end
def filters(&function)
proc { |accumulator, value|
if function.call(value)
accumulator << value
else
accumulator
end
}
end
[1,2,3,4,5]
.reduce([], &maps { |v| v * 3 })
.reduce([], &filters { |v| v.even? })
# => [6, 12]
def mapping(&function)
proc { |reducing_function|
proc { |accumulator, value|
reducing_function.call(accumulator, function.call(value))
}
}
end
def filtering(&function)
proc { |reducing_function|
proc { |accumulator, value|
if function.call(value)
reducing_function.call(accumulator, value)
else
accumulator
end
}
}
end
concats = proc { |accumulator, value| accumulator << value }
[1,2,3,4,5]
.reduce([], &mapping { |v| v * 3 }.call(concats))
.reduce([], &filtering { |v| v.even? }.call(concats))
# => [6, 12]
# gem install ramda-ruby
require 'ramda'
[1,2,3,4,5].reduce([], &Ramda.pipe(
mapping { |v| v + 1 },
filtering { |v| v.even? },
mapping { |v| v * 3 }
).call(concats))
# => [7, 13]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment