Skip to content

Instantly share code, notes, and snippets.

@darkslategrey
Forked from domgetter/transducers.rb
Created December 22, 2015 10:07
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 darkslategrey/eeb8c3efe5ec3a935b48 to your computer and use it in GitHub Desktop.
Save darkslategrey/eeb8c3efe5ec3a935b48 to your computer and use it in GitHub Desktop.
map = -> f {
-> rf {
-> acc, elem {
rf[acc, f[elem]]
}
}
}
square = -> n { n**2 }
add = -> acc, n { acc + n }
[1,2,3].reduce(0, &map[square][add])
#=> 14
notify = -> n {puts "Working on: #{n}"; n}
[1,2,3].reduce(0, &map[notify][add])
# Working on: 1
# Working on: 2
# Working on: 3
#=> 6
# We can compose these nicely
notify_then_square = -> n { square[notify[n]] }
[1, 2, 3].reduce(0, &map[notify_then_square][add])
# Working on: 1
# Working on: 2
# Working on: 3
#=> 14
square_then_notify = -> n { notify[square[n]] }
[1, 2, 3].reduce(0, &map[square_then_notify][add])
# Working on: 1
# Working on: 4
# Working on: 9
#=> 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment