Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

foldr and foldl in Ruby (See related posts)

module Enumerable
  def foldr(o, m = nil)
    reverse.inject(m) {|m, i| m ? i.send(o, m) : i}
  end

  def foldl(o, m = nil)
    inject(m) {|m, i| m ? m.send(o, i) : i}
  end
end

[1, 2, 3, 4, 5].foldl(:+) #=> 15
[1, 2, 3, 4, 5].foldl(:*) #=> 120

[1, 2, 3, 4, 5].foldr(:-, 0) #=> 3
[1, 2, 3, 4, 5].foldl(:-, 0) #=> -15



You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts