Search code examples
elmparser-combinators

Parsing dice notation with Elm


I am trying to write a small dice notation (e.g. "2d6", where 2 is the count and 6 is the die size) parser using the library in elm-tools/parser.

An expression should be in the form

[int] "d" int

but I can't figure out to parse the optional leading int (which will default to 1 if it is missing).

So far, I've come up with this:

import Parser exposing (..)


type alias Roll =
    { count : Int
    , size : Int
    }


die : Parser Int
die =
    succeed identity
        |. keyword "d"
        |= int

and I would like the parser to return a Roll on a successful parse, but I'm not sure how to proceed.

I am guessing that I will need to make use of oneOf, but I'm not sure how.

Unfortunately, I can't find any good examples of using this library.


Solution

  • Thanks to @Chad's answer (https://stackoverflow.com/a/45620875/96233), I got it working with this:

    type alias Dice =
        { count : Int
        , size : Int
        }
    
    
    dice : Parser Dice
    dice =
        succeed Dice
            |= count
            |. spaces
            |. keyword "d"
            |. spaces
            |= integer
    
    
    count : Parser Int
    count =
        oneOf
            [ integer |> andThen succeed
            , succeed 1
            ]
    
    
    integer : Parser Int
    integer =
        keep oneOrMore isDigit
            |> andThen
                (\s ->
                    case String.toInt s of
                        Ok value ->
                            succeed value
    
                        Err err ->
                            fail err
                )
    
    
    spaces : Parser ()
    spaces =
        ignore zeroOrMore (\c -> c == ' ')