Last active
June 25, 2020 11:27
-
-
Save shamansir/4646370f20c3be75ba7e394de244a335 to your computer and use it in GitHub Desktop.
Elm parser loop example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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