Class: Patm::Pattern::Arr

Inherits:
Patm::Pattern show all
Defined in:
lib/patm.rb

Instance Method Summary collapse

Methods inherited from Patm::Pattern

#&, #[], build_from, build_from_array, build_from_hash, #compile, #opt, #opt?, #rest?

Constructor Details

#initialize(head, rest = nil, tail = []) ⇒ Arr

Returns a new instance of Arr.



204
205
206
207
208
# File 'lib/patm.rb', line 204

def initialize(head, rest = nil, tail = [])
  @head = head
  @rest = rest
  @tail = tail
end

Instance Method Details

#compile_internal(free_index, target_name = "_obj") ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/patm.rb', line 239

def compile_internal(free_index, target_name = "_obj")
  i = free_index
  srcs = []
  ctxs = []

  srcs << "#{target_name}.is_a?(::Array)"

  i = compile_size_check(target_name, srcs, ctxs, i)

  i = compile_part(target_name, @head, srcs, ctxs, i)

  unless @tail.empty?
    srcs << "#{target_name}_t = #{target_name}[(-#{@tail.size})..-1]; true"
    i = compile_part("#{target_name}_t", @tail, srcs, ctxs, i)
  end

  i = compile_rest(target_name, srcs, ctxs, i)

  [
    srcs.compact.map{|s| "(#{s})"}.join(" &&\n"),
    ctxs.flatten(1),
    i
  ]
end

#execute(mmatch, obj) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/patm.rb', line 210

def execute(mmatch, obj)
  return false unless obj.is_a?(Array)

  size_min = @head.size + @tail.size
  if @rest
    return false if obj.size < size_min
  else
    return false if obj.size != size_min
  end

  return false unless @head.zip(obj[0..(@head.size - 1)]).all? {|pat, o|
    pat.execute(mmatch, o)
  }

  return false unless @tail.zip(obj[(-@tail.size)..-1]).all? {|pat, o|
    pat.execute(mmatch, o)
  }

  !@rest || @rest.execute(mmatch, obj[@head.size..-(@tail.size+1)])
end

#inspectObject



231
232
233
234
235
236
237
# File 'lib/patm.rb', line 231

def inspect
  if @rest
    (@head + [@rest] + @tail).inspect
  else
    (@head + @tail).inspect
  end
end