0

I've just started using Scala a few days ago and wanted to write my first parser.

the problematic code is as follows:

  val withoutZero: Parser[List[String]] = ("1" | "2" | "3" | "4").+
  val withZero: Parser[String] = "0" | withoutZero

the number string I'd like to parse can have multiple zeros and other numbers but I want to define two functions for it.

the combined withZero has to stay String (not List[String] or whatever else). at the moment I'm only parsing one zero because ("0").+ didn't work out.

my question: how am I able to adjust the withZero Parser to multiple zeros AND combining it with the withoutZero Parser still staying a Parser[String]

3
  • Can you give some examples of grammatical strings? It's not entirely clear to me from your description. Commented May 1, 2015 at 17:44
  • it should parse: 0+ | (1|2|3|4)+ Commented May 1, 2015 at 17:56
  • The stuff on either side of the | has to be the same type, so I still don't understand—it guess I'd still like to see actual strings. Commented May 1, 2015 at 18:21

1 Answer 1

1

I think this should work for 0+ | (1|2|3|4)+:

val withZero: Parser[String] = (literal("0").+ | withoutZero) ^^ (_.mkString)

It joins the list of Strings from some parser into a single String

Sign up to request clarification or add additional context in comments.

3 Comments

thanks only problem: value mkString is not a member of java.io.Serializable
@TwelveDollar It's a member of scala.collection.TraversableOnce and via inheritance member of List and all other collections. Do you have anything else within parenthese? Some of the Parsers in the parentheses is not a Parser[List[String]], it seems. It works as seen here: tutorialspoint.com/…
okay thanks, can't see any mistake copied your tutorialspoint code resulting in the same error. I'll fix that myself. code works as intended therefore answer accepted. (y)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.