Return to Snippet

Revision: 269
at July 8, 2006 08:06 by yaguta


Initial Code
require 'active_support/binding_of_caller'

class Intention
  def initialize(value_expression, var, source)
    @value_expression = value_expression
    @var = var
    @source = source
  end
  
  def to_a(predicates, binding)
    predicates << 'true'  if predicates == []
    eval(<<-EOF, binding)
      #@source.select {|#@var|  #{predicates.join('&&')} }.map do |#@var|
        #@value_expression
      end
    EOF
  end
end

class String
  def |(other)
    raise  unless other =~ /^(.+)<-(.+)$/
    Intention.new(self, $1, $2)
  end
end

class I
  def self.[](intention, *predicates)
    raise  unless  intention.instance_of?(Intention)
    Binding.of_caller do |binding|
      intention.to_a(predicates, binding)
    end
  end
end

=begin Example
xs = [10,30,3,-5,1,10,100,-60]
p I['(x*2).abs' | 'x<-xs', 'x < 50']
#=> [20, 60, 6, 10, 2, 20, 120]

def quicksort(x = nil, *xs)
  return []  if x == nil
  quicksort(*I['y' | 'y <- xs', 'y < x']) + [x] + quicksort(*I['y' | 'y <- xs', 'y >= x'])
end
p quicksort(*xs)
#=> [-60, -5, 1, 3, 10, 10, 30, 100]
=end

Initial URL


Initial Description


Initial Title
List intention expression

Initial Tags
ruby

Initial Language
Ruby