type Parser a = String -> [(a, String)]
文字列を受け取ると、それをパースした型aの結果と、消費されなかった文字列のペアのリストを返す、という型になっている。返り値のリストが空であることが失敗を表す。
|
|
|
|
> | parse (return 1) "abc" |
[(1, "abc")] | |
> | parse failure "abc" |
[] | |
> | parse item "abc" |
[('a', "bc")] |
|
p :: Parser (Char, Char) p = item >= \x -> item >= const item >= \y -> return (x, y) |
> | parse p "abcdef" |
[(('a', 'c'), "def")] | |
> | parse p "ab" |
[] |
|
> | parse (failure +++ return 'd') "abc" |
[('d', "abc")] | |
> | parse (item +++ return 'd') "abc" |
[('a', "abc")] |
|
・ | digit | :: Parser Char |
digit | = sat isDigit |
・ | lower | :: Parser Char |
lower | = sat isLower |
・ | upper | :: Parser Char |
upper | = sat isUpper |
・ | alphanum | :: Parser Char |
alphanum | = sat isAlphaNum |
・ | char | :: Char -> Parser Char |
char x | = sat (==x) |
> | parse digit "123" |
[('1', "23")] | |
> | parse (char 'a') "abc" |
[('a', "abc")] |
|
> | parse (string "abc") "abcdef" |
[("abc", "def")] | |
> | parse (string "abc") "ab1234" |
[] |
|
> | parse (many digit) "123abc" |
[("123", "abc")] | |
> | parse (many digit) "ab1234" |
[("", "ab1234")] | |
> | parse (many1 digit) "ab1234" |
[] |
|
nat | :: | Parser Int |
space | :: | Parser () |
|
> | parse (token nat) " 123 " |
[(123, "")] |
|
|
expr | := | term '+' expr | expr '-' term | term |
term | := | factor '*' term | term '/' factor | factor |
factor | := | '(' expr ')' | nat |
nat | := | '0' | '1' | '2' | ... |
expr | := | term '+' expr | expr '-' term | term |
term | := | power '*' term | term '/' power | power |
power | := | factor '^' power | factor |
factor | := | '(' expr ')' | nat |
nat | := | '0' | '1' | '2' | ... |
expr | := | expr '-' factor | factor |
factor | := | '(' expr ')' | nat |
nat | := | '0' | '1' | '2' | ... |
|
|
|
|