name.rayrobdod.stringContextParserCombinator.typeclass.Repeated
See theRepeated companion object
Describes how to combine a homogeneous sequence of zero-or-more values.
When a Repeated is used:
- first,
init
to create an initial value for the accumulator - then,
append
is called once for each component item in order, using the accumulator and the component item as parameters and returning the next accumulator value - lastly,
result
is called with the final accumulator value, and the result of this call is overall result.
init
will be called anew on each use, so it is possible to use a mutable accumulator by creating a new builder in the init
method and returning the acc
parameter in the append method.
Below is an example of implementing and using a custom Repeated
:
import name.rayrobdod.stringContextParserCombinator.Interpolator.charIn
import name.rayrobdod.stringContextParserCombinator.Interpolator.idInterpolators
import name.rayrobdod.stringContextParserCombinator.typeclass.Repeated
// define the marker types
case class Digit(value:Int)
case class Digits(value:Int)
// define the given instance
given Repeated[Digit, Digits] with {
type Acc = Int
def init():Acc = 0
def append(acc:Acc, elem:Digit):Acc = (acc * 10) + elem.value
def result(acc:Acc):Digits = new Digits(acc)
}
// create the parsers
val digit:idInterpolators.Interpolator[Digit] = charIn('0' to '9').map(x => Digit(x - '0'))
val digits:idInterpolators.Interpolator[Digits] = digit.repeat(1)// using Repeated[Digit, Digits]
// use the parser
digits.interpolate(StringContext("1234"), Nil) // Digits(1234): Digits
Type parameters
- A
-
the repeated input elements
- Z
-
the result container
Attributes
- See also
- Companion
- object
- Source
- Repeat.scala
- Graph
-
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
-
Members list
In this article