elm/parser
Regular expressions are quite confusing and difficult to use. This library provides a coherent alternative that handles more cases and produces clearer code.
(Readme.md from the package)
type alias Point =
{ x : Float
, y : Float
}
point : Parser Point
point =
succeed Point
|. symbol "("
|. spaces
|= float
|. spaces
|. symbol ","
|. spaces
|= float
|. spaces
|. symbol ")"
This is a summary of the talk Demystifying Parsers by Tereza Sokol.
Basics
Function
Description
run : Parser a -> String -> Result (List DeadEnd) a
Runs the Parser on a String
int : Parser Int
Parser for Int
float : Parser Float
Parser for Float
oneOf : List (Parser a) -> Parser a
Trys different Parsers. Uses the first that succeeds.
Once the parser matches the first element, there is no going back!
andThen : (a -> Parser b) -> Parser a -> Parser b
Applys the first parser and if successful applies the second. Fails if one of the parsers fails.
Pipeline
Function
Description
succeed : a -> Parser a
Starts the Pipeline. a -> Parser a
is the constructor.
For a record Point
use the structur called Point .
(|=) : Parser (a -> b) -> Parser a -> Parser b
Keeps an element.
(|.) : Parser keep -> Parser ignore -> Parser keep
Eats a character and throws it away.
spaces : Parser ()
Represents whitespace
Strings
Function
Description
chompWhile : (Char -> Bool) -> Parser ()
Looks for zero or more characters that succeeds the check. Stops as soon as the check fails.
chompIf : (Char -> Bool) -> Parser ()
Reads one symbols.
getChompedString : Parser a -> Parser String
Returnes the string that got chomped
Loops
Error messages
Function
Description
problem : String -> Parser a
Returns the error message and ends the parsing. The argument is the actuall message.
Further Reading
🎥Video: Demystifying Parsers by Tereza Sokol
📄Thread: Elm parser question
Last updated
Was this helpful?