|
| 1 | +module Main exposing (..) |
| 2 | + |
| 3 | +import Test exposing (Test, describe, test) |
| 4 | +import Expect |
| 5 | + |
| 6 | +suite : Test |
| 7 | +suite = |
| 8 | + describe "Parser" |
| 9 | + [ test "s" <| |
| 10 | + \_ -> |
| 11 | + let |
| 12 | + ret = parse string "hoge" |
| 13 | + in |
| 14 | + Expect.equal ret ["hoge"] |
| 15 | + ] |
| 16 | + |
| 17 | +{- |
| 18 | +import Html exposing (Html) |
| 19 | +
|
| 20 | +main : Html Never |
| 21 | +main = |
| 22 | + let |
| 23 | + p = s "users" |
| 24 | + |> slash string |
| 25 | + |> slash (s "posts") |
| 26 | + |> slash int |
| 27 | + |> map Tuple.pair |
| 28 | + ret = parse p "users/nojima/posts/3" |
| 29 | + in |
| 30 | + Html.pre [] |
| 31 | + [ Html.text "Hello, World" |
| 32 | + , Html.text (Debug.toString ret) ] |
| 33 | +-} |
| 34 | + |
| 35 | +type alias Parser a b = |
| 36 | + State a -> List (State b) |
| 37 | + |
| 38 | +type alias State value = |
| 39 | + { tokens : List String |
| 40 | + , value : value |
| 41 | + } |
| 42 | + |
| 43 | +map : a -> Parser a b -> Parser (b -> c) c |
| 44 | +map subValue parseArg = |
| 45 | + \state -> |
| 46 | + parseArg { tokens = state.tokens, value = subValue } |
| 47 | + |> List.map (mapState state.value) |
| 48 | + |
| 49 | +mapState : (a -> b) -> State a -> State b |
| 50 | +mapState func state = |
| 51 | + { tokens = state.tokens, value = func state.value } |
| 52 | + |
| 53 | +tokenize : String -> List String |
| 54 | +tokenize str = |
| 55 | + String.split "/" str |
| 56 | + |
| 57 | +parse : Parser (a -> a) a -> String -> List a |
| 58 | +parse parser str = |
| 59 | + let |
| 60 | + initialState = |
| 61 | + { tokens = tokenize str |
| 62 | + , value = identity |
| 63 | + } |
| 64 | + in |
| 65 | + parser initialState |
| 66 | + |> List.map (\state -> state.value) |
| 67 | + |
| 68 | +int : Parser (Int -> a) a |
| 69 | +int = |
| 70 | + custom String.toInt |
| 71 | + |
| 72 | +string : Parser (String -> a) a |
| 73 | +string = |
| 74 | + custom Just |
| 75 | + |
| 76 | +custom : (String -> Maybe a) -> Parser (a -> b) b |
| 77 | +custom stringToSomething = |
| 78 | + \state -> |
| 79 | + case state.tokens of |
| 80 | + [] -> [] |
| 81 | + head :: tail -> |
| 82 | + case stringToSomething head of |
| 83 | + Nothing -> [] |
| 84 | + Just nextValue -> |
| 85 | + [ { tokens = tail, value = state.value nextValue } ] |
| 86 | + |
| 87 | +s : String -> Parser a a |
| 88 | +s str = |
| 89 | + \state -> |
| 90 | + case state.tokens of |
| 91 | + [] -> [] |
| 92 | + head :: tail -> |
| 93 | + if head == str |
| 94 | + then [ { tokens = tail, value = state.value } ] |
| 95 | + else [] |
| 96 | + |
| 97 | +slash : Parser a b -> Parser b c -> Parser a c |
| 98 | +slash lhs rhs = |
| 99 | + \state -> |
| 100 | + lhs state |
| 101 | + |> List.concatMap rhs |
0 commit comments