Class: Yaparc::Seq

Inherits:
Object
  • Object
show all
Includes:
Parsable
Defined in:
lib/yaparc/seq.rb

Constant Summary

Constants included from Parsable

Parsable::IS_ALPHANUM, Parsable::IS_CR, Parsable::IS_DIGIT, Parsable::IS_LOWER, Parsable::IS_SPACE, Parsable::IS_WHITESPACE

Instance Method Summary collapse

Methods included from Parsable

#parse

Constructor Details

#initialize(*parsers) ⇒ Seq

Returns a new instance of Seq.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/yaparc/seq.rb', line 7

def initialize(*parsers)
  @parser = lambda do |input|
    args = []
    initial_result = OK.new(input:)
    final_result = parsers.inject(initial_result) do |subsequent, parser|
      result = parser.parse(subsequent.input)
      break Fail.new(input: subsequent.input) if result.instance_of?(Fail)

      args << result.value
      result
    end

    case final_result
    in Fail
      Fail.new(input: final_result.input)
    in OK
      final_value = if block_given?
                      yield(*args)
                    else
                      args.last
                    end
      OK.new(value: final_value, input: final_result.input)
    end
  end
end