列表意图表达
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表意图表达相关的知识,希望对你有一定的参考价值。
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
以上是关于列表意图表达的主要内容,如果未能解决你的问题,请参考以下文章