# $Id: enumerable.rb,v 1.2 2002/05/03 21:03:56 knu Exp $

require 'features/ruby18/base'

module Enumerable
  def all?
    each { |e| yield(e) or return false }
    true
  end

  def any?
    each { |e| yield(e) and return true }
    false
  end

  def inject(*argv)
    argc = argv.size

    if argc == 0
      first = true
      result = nil

      each { |e|
	if first
	  first = false
	  result = e
	else
	  result = yield(result, e)
	end
      }
    elsif argc == 1
      result = argv[0]

      each { |e| result = yield(result, e) }
    else
      raise ArgumentError, "wrong # of arguments(#{argc} for 1)"
    end

    result
  end

  def partition
    a = []
    b = []
    each do |x|
      if yield(x)
	a << x
      else
	b << x
      end
    end

    return a, b
  end

  def sort_by
    ary = map { |i| [yield(i), i] }
    ary.sort! { |a, b| a[0] <=> b[0] }
    ary.map! { |i| i[1] }
  end
end
