[#2367] Standard libraries — Dave Thomas <dave@...>

From ruby-dev summary:

60 messages 2004/02/11

[#2397] PATCH: deprecate cgi-lib, getopts, importenv, parsearg from standard library — Gavin Sinclair <gsinclair@...>

Index: cgi-lib.rb

15 messages 2004/02/12

[#2465] PATCH: OpenStruct#initialize to yield self — Gavin Sinclair <gsinclair@...>

This is a common approach I use to object initialization; I don't know

24 messages 2004/02/19

foldl and foldr

From: "Sean E. Russell" <ser@...>
Date: 2004-02-25 14:29:31 UTC
List: ruby-core #2504
Sorry if I'm opening old wounds; I have a hard time believing that nobody has 
asked for foldr and foldl for arrays yet, but here goes:

I'd like to see Array and Enumerable modified to include foldr and foldl.  The 
methods are simple, and are defined below for convenience.  They're easy 
enough to define by one's self, but find that I reach for them enough that I 
think they'd be generally useful, and should be included in the standard 
class definitions.  A bonus would be having them defined in native C.

For those not familiar to these methods, they're from the functional 
programming space, and they allow you to combine array contents.  They're 
generalizations of the "join()" function.

Example: the sum of all numbers between 1 and 100:
Current: 
	sum = 0
	(1..100).to_a.each {|x| sum += x}
	puts sum
New:
	puts ((1..100).to_a.foldl(0) {|a,b| a+b})


Example: 
Current:
	x = 54
	[12,4,10,6].reverse.each{ |y| x = (x+y)/2 }
New:
	x = [12,4,10,6].foldr(54) {|a,b| (a+b)/2}


There isn't anything you can do with foldr and foldl that you can't already 
do, but there are some things that you can do with less code, more elegantly, 
with foldr and foldl than you can with the current methods.

foldl() folds from the left, and so can work with any Enumerable.  Therefore, 
I propose foldl() as an addition to Enumerable.  foldr() folds from the 
right, and requires either reversing the array (more costly in time and 
space), or having access to the index, both of which require an Array object; 
therefore, it belongs in Array.


class Array
  def foldr a
    (length-1).downto(0) { |i| a = yield self[i], a }
    return a
  end
end

module Enumerable
  def foldl a
    each { |b| a = yield a, b }
    return a
  end
end

-- 
### SER   
### Deutsch|Esperanto|Francaise|Linux|XML|Java|Ruby|Aikido
### http://www.germane-software.com/~ser  jabber.com:ser  ICQ:83578737 
### GPG: http://www.germane-software.com/~ser/Security/ser_public.gpg

In This Thread

Prev Next