gluon-lang / gluon

A static, type inferred and embeddable language written in Rust.
https://gluon-lang.org
MIT License
3.16k stars 145 forks source link

Wish example parsing CSV #920

Open frehberg opened 2 years ago

frehberg commented 2 years ago

Hi,

I would like to use gluon to parse CSV files. I am stuck implementing a CSV parser myself. I would appreciate to find an example in github repo, a parser for CSV strings, maybe covering quoted elements as well.

I did a first draft, but I am stuck. The following simple parser is just parsing the first line. Any idea what combinator is missing to consume the newline and to parse the second line?

let io @ { ? } = import! std.io
let prelude = import! std.prelude
let { Result } = import! std.result
let { (*>), (<*), wrap } = import! std.applicative
let list @ { List } = import! std.list
let csv = "11,12,13\n21,22,23"

let parse : String -> Result String (List (List String)) =
  let { (<|>) } = import! std.alternative
  let parser @ {
        spaces,
        token,
        digit,
        skip_many1,
        recognize,
        sep_by1,
        (<?>),
        ? } = import! std.parser
  let int = import! std.int
  let lex x = x <* spaces
  let literal =
        do i = lex (recognize (skip_many1 digit))
        wrap i
  let record = sep_by1 literal (token ',')
  let records = sep_by1 record (token '\n')
  let parse = parser.parse (records <* spaces)
  parse

let result = parse csv
result