-
I need to have a stateful parser in my program. I see that registers are intended for that, but could you please share some examples how then? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
For example, supposing I had to parse a date string: "2023-03-14". I need to check if separators are the same, or report an parse error.
But that doesn't work. So I think my approach is wrong. |
Beta Was this translation helpful? Give feedback.
-
So this is what I ended up with, but I am not sure I like it, right? Because join and flatmap are inefficient, so any tips for improve? |
Beta Was this translation helpful? Give feedback.
-
What you want is basically a def charReg(r: Reg[Char]): Parsley[Char] = r.gets(char(_)).flatten The problem is that this combinator would be implemented by I would also love to add some examples of registers too, it is absolutely on my TODO list. To be clear about the Instead, I think what I posted above fixes your problem more directly: import parsley.implicits.zipped.Zipped5
import parsley.errors.combinator._
(yearorintp, datesepchar, natural, datesepchar, natural).zipped.collectMsg("This date is malformed because the separators are different.") {
case (year, sep1, month, sep2, day) if sep1 == sep2 => Try(LocalDate.of(year, month, day)).toOption
}.collectMsg("this data is invalid, please correct it") {
case Some(d) => d.toString
} |
Beta Was this translation helpful? Give feedback.
-
Thank you! |
Beta Was this translation helpful? Give feedback.
What you want is basically a
charReg
combinator, as I understand it:The problem is that this combinator would be implemented by
flatten
(orjoin
as you'd call it), and as you note this is inefficient. I haven't implemented a built-in version ofcharReg
/satisfyReg
yet, which would be efficient, but that is something I do want to add when I get some spare time again!I would also love to add some examples of registers too, it is absolutely on my TODO list. To be clear about the
charReg
combinator above, I'm envisioning you'd use it likesepReg.put(datesepchar)
and then usecharReg(sepReg)
for the second invokation.Instead,…