List intention expression


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'active_support/binding_of_caller'
  2.  
  3. class Intention
  4. def initialize(value_expression, var, source)
  5. @value_expression = value_expression
  6. @var = var
  7. @source = source
  8. end
  9.  
  10. def to_a(predicates, binding)
  11. predicates << 'true' if predicates == []
  12. eval(<<-EOF, binding)
  13. #@source.select {|#@var| #{predicates.join('&&')} }.map do |#@var|
  14. #@value_expression
  15. end
  16. EOF
  17. end
  18. end
  19.  
  20. class String
  21. def |(other)
  22. raise unless other =~ /^(.+)<-(.+)$/
  23. Intention.new(self, $1, $2)
  24. end
  25. end
  26.  
  27. class I
  28. def self.[](intention, *predicates)
  29. raise unless intention.instance_of?(Intention)
  30. Binding.of_caller do |binding|
  31. intention.to_a(predicates, binding)
  32. end
  33. end
  34. end
  35.  
  36. =begin Example
  37. xs = [10,30,3,-5,1,10,100,-60]
  38. p I['(x*2).abs' | 'x<-xs', 'x < 50']
  39. #=> [20, 60, 6, 10, 2, 20, 120]
  40.  
  41. def quicksort(x = nil, *xs)
  42.   return [] if x == nil
  43.   quicksort(*I['y' | 'y <- xs', 'y < x']) + [x] + quicksort(*I['y' | 'y <- xs', 'y >= x'])
  44. end
  45. p quicksort(*xs)
  46. #=> [-60, -5, 1, 3, 10, 10, 30, 100]
  47. =end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.