[elm/parser]: how to handle optional-with-default scenario?

I’m struggling to wrap my head around this, grateful for any help.

First off, I want to populate this type:

type alias Entity = 
    { name : String
    , plural : String
    }

Scenario 1: plural explicitly specified:

run parseEntity "Entity Sheep plural Sheep" == Ok {name = "Sheep", plural = "Sheep"}

Scenario 2: plural not specified, derived by adding ‘s’ to name:

run parseEntity "Entity Dog" == Ok {name = "Dog", plural = "Dogs"}

A parser function for scenario 1 only is straightforward:

parseEntity : Parser Entity
parseEntity =
    succeed Entity
        |. keyword "Entity"
        |. spaces
        |= parseVarName
        |. spaces
        |. keyword "plural"
        |. spaces
        |= parseVarName

where parseVarName just wraps the variable function & returns a string. I’m struggling to figure out how to extend this to cover scenario 2. Intuitively, I can see that oneOf is likely part of the answer - and possibly map to set the default? Putting them together proving elusive however.

Thanks for any help.

You are on good track with Parser.oneOf, but you also need Parser.andThen to return the plural from the singular if it was not specified:

parseEntity : Parser Entity
parseEntity =
    succeed identity
        |. keyword "Entity"
        |. spaces
        |= parseVarName
        |> andThen parseEntityPlural


parseEntityPlural : String -> Parser Entity
parseEntityPlural entity =
    oneOf
        [ succeed (Entity entity)
            |. spaces
            |. keyword "plural"
            |. spaces
            |= parseVarName
        , succeed (Entity entity (entity ++ "s"))
        ]


parseVarName : Parser String
parseVarName =
    variable
        { start = Char.isAlpha
        , inner = Char.isAlpha
        , reserved = Set.empty
        }

https://ellie-app.com/6dPtKcnJZKVa1

Wonderful - deeply appreciated, thank you very much.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.