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

About this user

Sharon Rosner http://hiperu.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

foldr and foldl in Ruby

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


« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS