Skip to content

Commit

Permalink
🎨 refactor many to use generics
Browse files Browse the repository at this point in the history
  • Loading branch information
nabeelvalley committed Jul 19, 2024
1 parent b155520 commit 3652da3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
13 changes: 8 additions & 5 deletions src/parz/combinators.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,18 @@ pub fn maybe(parser) {
}
}

fn many_rec(parser: Parser(a), input, acc) {
fn many_rec(
parser: Parser(a),
input,
acc,
) -> Result(ParserState(List(a)), String) {
case parser(input) {
Error(err) -> Error(err)
Ok(ok) -> {
case many_rec(parser, ok.remaining, acc) {
Error(_) -> Ok(#([ok.matched], ok.remaining))
Error(_) -> Ok(ParserState([ok.matched], ok.remaining))
Ok(rec) -> {
let #(matches, remaining) = rec
Ok(#([ok.matched, ..matches], remaining))
Ok(ParserState([ok.matched, ..rec.matched], rec.remaining))
}
}
}
Expand All @@ -113,7 +116,7 @@ pub fn many1(parser: Parser(a)) {
pub fn many(parser: Parser(a)) {
fn(input) {
case many1(parser)(input) {
Error(_) -> Ok(#([], input))
Error(_) -> Ok(ParserState([], input))
Ok(ok) -> Ok(ok)
}
}
Expand Down
14 changes: 7 additions & 7 deletions test/combinators_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,19 @@ pub fn many_test() {

run(parser, "!")
|> should.be_ok
|> should.equal(#([], "!"))
|> should.equal(ParserState([], "!"))

run(parser, "x")
|> should.be_ok
|> should.equal(#(["x"], ""))
|> should.equal(ParserState(["x"], ""))

run(parser, "xxx")
|> should.be_ok
|> should.equal(#(["x", "x", "x"], ""))
|> should.equal(ParserState(["x", "x", "x"], ""))

run(parser, "xx!")
|> should.be_ok
|> should.equal(#(["x", "x"], "!"))
|> should.equal(ParserState(["x", "x"], "!"))
}

pub fn many1_test() {
Expand All @@ -106,15 +106,15 @@ pub fn many1_test() {

run(parser, "x")
|> should.be_ok
|> should.equal(#(["x"], ""))
|> should.equal(ParserState(["x"], ""))

run(parser, "xxx")
|> should.be_ok
|> should.equal(#(["x", "x", "x"], ""))
|> should.equal(ParserState(["x", "x", "x"], ""))

run(parser, "xx!")
|> should.be_ok
|> should.equal(#(["x", "x"], "!"))
|> should.equal(ParserState(["x", "x"], "!"))
}

pub fn sequence_test() {
Expand Down

0 comments on commit 3652da3

Please sign in to comment.