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

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

foldr and foldl in Ruby

   1  
   2  module Enumerable
   3    def foldr(o, m = nil)
   4      reverse.inject(m) {|m, i| m ? i.send(o, m) : i}
   5    end
   6  
   7    def foldl(o, m = nil)
   8      inject(m) {|m, i| m ? m.send(o, i) : i}
   9    end
  10  end
  11  
  12  [1, 2, 3, 4, 5].foldl(:+) #=> 15
  13  [1, 2, 3, 4, 5].foldl(:*) #=> 120
  14  
  15  [1, 2, 3, 4, 5].foldr(:-, 0) #=> 3
  16  [1, 2, 3, 4, 5].foldl(:-, 0) #=> -15


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