Skip to content

Instantly share code, notes, and snippets.

@shamansir
Last active June 25, 2020 11:27
Show Gist options
  • Save shamansir/4646370f20c3be75ba7e394de244a335 to your computer and use it in GitHub Desktop.
Save shamansir/4646370f20c3be75ba7e394de244a335 to your computer and use it in GitHub Desktop.
Elm parser loop example
module Main exposing (main)
import Browser
import Html exposing (Html, button, div, h2, input, text)
import Html.Attributes exposing (class, placeholder, value)
import Html.Events exposing (onClick, onInput)
import Parser exposing (..)
import Parser as P exposing (..)
type Atom
= Foo
| Bar
| Eee
| Nnn
| Unknown
main =
Html.text <|
Debug.toString <|
run urlParser "/foo/foo/bar/eee/nnn/x:0x9"
urlParser : Parser (List Atom)
urlParser =
loop [] fragmentsStep
|> P.map (List.map <| P.run atom)
|> P.map (List.map Result.toMaybe)
|> P.map (List.filterMap identity)
atom : Parser Atom
atom =
P.oneOf
[ P.succeed Foo |. P.symbol "foo"
, P.succeed Bar |. P.symbol "bar"
, P.succeed Eee |. P.symbol "eee"
, P.succeed Nnn |. P.symbol "nnn"
, P.succeed Unknown
]
fragmentsStep : List String -> Parser (Step (List String) (List String))
fragmentsStep stmt =
let
isAtomChar c = Char.isAlphaNum c || c == ':'
f acc num =
if String.length num > 0 then
Loop (num :: acc)
else
Done (List.reverse acc)
in
oneOf
[ succeed (f stmt)
|. symbol "/"
|= (chompWhile isAtomChar
|> getChompedString)
, succeed (f stmt)
|= (chompWhile isAtomChar
|> getChompedString)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment