r/functionalprogramming • u/OrneryEntrepreneur55 • Jun 05 '25
Question I need help with parser combinators
Hello everyone.
I have to parse some text in Gleam.
I use party and I'd like a parser that parses any character n times.
I wrote this:
fn parse_n(chars: List(String), n: Int) -> Parser(List(String), String) -> Parser(List(String), String){
case n {
0 -> return(chars)
_ -> {
use char <- do(party.any_char())
parse_n([char, ..chars], n - 1)
}
}
}But it is not tail recursive.
I'd like a tail recursive version or a version that uses stateful_many.
Can someone help?
Thanks
Edit: for the people not familiar with Gleam, here is the Haskell equivalent
any_char :: Parser Char
parse_n :: [Char] -> Int -> Parser [Char]
parse_n chars 0 = chars
parse_n chars n =
do
char <- any_char
parse_n (char : chars) (n - 1)Also, this is the signature of stateful_many in Gleam
pub fn stateful_many(
state: a,
p: Parser(fn(a) -> #(b, a), c),
) -> Parser(#(List(b), a), c)And in Haskell
stateful_many :: state -> (state -> (state, output)) -> Parser (state, [output])I think this could help me even though I struggle to use it because of its signature (skill issue)
7
Upvotes
View all comments
Show parent comment
1
u/OrneryEntrepreneur55 Jun 06 '25 edited Jun 06 '25
That's because use notation in Gleam is a syntactic sugar that hides some of the flow like the do notation in Haskell. That's the de sugared version of the code
Here is the Haskell version of the original listing
And btw, you're right, the list should be reversed.