Class: Cohi::Function
- Inherits:
-
Object
- Object
- Cohi::Function
- Defined in:
- lib/cohi.rb
Instance Method Summary collapse
- #*(f) ⇒ Object
- #**(*xs) ⇒ Object
- #[](*xs) ⇒ Object
- #add(pat, &f) ⇒ Object
-
#initialize(sym) ⇒ Function
constructor
A new instance of Function.
- #match_pattern?(pat, xs) ⇒ Boolean
Constructor Details
#initialize(sym) ⇒ Function
Returns a new instance of Function.
9 10 11 12 |
# File 'lib/cohi.rb', line 9 def initialize(sym) @sym = sym @func = [] end |
Instance Method Details
#*(f) ⇒ Object
59 60 61 |
# File 'lib/cohi.rb', line 59 def *(f) lambda {|*xs| self[f[*xs]] } end |
#**(*xs) ⇒ Object
63 64 65 |
# File 'lib/cohi.rb', line 63 def **(*xs) self[*xs] end |
#[](*xs) ⇒ Object
18 19 20 21 22 23 24 25 |
# File 'lib/cohi.rb', line 18 def [](*xs) @func.each do |func| pat, f = *func xs2 = match_pattern?(pat, xs) return f[*xs2] if xs2 end raise(ArgumentError, "no match pattern. `#{@sym}' #{xs.inspect}") end |
#add(pat, &f) ⇒ Object
14 15 16 |
# File 'lib/cohi.rb', line 14 def add(pat, &f) @func.push([pat, f]) end |
#match_pattern?(pat, xs) ⇒ Boolean
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/cohi.rb', line 27 def match_pattern?(pat, xs) return xs unless pat return nil if not pat.include?(XS) and pat.size != xs.size rs = [] pat.each_with_index do |pt, i| x = xs[i] case pt when Array xs3 = match_pattern?(pt, x) return nil unless xs3 rs += xs3 when X rs << x next when XS rs << [x, *xs[i + 1 .. -1]] xs = [] next when X_XS y, *ys = *x rs << y rs << ys next when x next else return nil end end rs end |