| Safe Haskell | Safe-Inferred |
|---|
Lessons.Lesson10
Description
Notes taken by Deimantė Davidavičiūtė
Synopsis
- type ErrorMsg = String
- type Input = String
- type Parser a = ExceptT ErrorMsg (State Input) a
- parseLetter :: Parser Char
- parseTwoLetters :: Parser String
- parseTwoLetters' :: Parser String
- parse :: Parser a -> Input -> (Either ErrorMsg a, Input)
- type Weird a = ExceptT Int (StateT String IO) a
- weird :: Weird Double
- weird' :: Weird Double
- data SomeData
Documentation
type ErrorMsg = String Source #
Basic types for the parser.
Parser a is an ExceptT over State.
State Input carries the remaining input string.
ExceptT ErrorMsg allows failure with an error message.
parseLetter :: Parser Char Source #
Parse a single alphabetic character.
Consumes one character from the input state or fails with an error message.
>>>parse parseLetter "a1"(Right 'a',"1")>>>parse parseLetter "1a"(Left "A letter is expected, but got 1","1a")>>>parse parseLetter ""(Left "A letter is expected but got empty input","")
parseTwoLetters :: Parser String Source #
Parse two letters using 'do' notation.
>>>parse parseTwoLetters "ds"(Right "ds","")>>>parse parseTwoLetters "d5"(Left "A letter is expected, but got 5","5")
parseTwoLetters' :: Parser String Source #
Same as parseTwoLetters, but using applicative style.
>>>parse parseTwoLetters' "ab"(Right "ab","")
parse :: Parser a -> Input -> (Either ErrorMsg a, Input) Source #
Running the parser:
>>>:t runExceptT parseTwoLettersrunExceptT parseTwoLetters :: State Input (Either ErrorMsg String)
>>>:t runState (runExceptT parseTwoLetters)runState (runExceptT parseTwoLetters) :: Input -> (Either ErrorMsg String, Input)
>>>parse parseTwoLetters ""(Left "A letter is expected but got empty input","")>>>parse parseTwoLetters "ds"(Right "ds","")>>>parse parseTwoLetters "545435"(Left "A letter is expected, but got 5","545435")
Helper to run a Parser on an input string.
type Weird a = ExceptT Int (StateT String IO) a Source #
A more complex monad stack: IO + State + Except.
Weird a fails with an Int, keeps a String state, and can do IO.
weird :: Weird Double Source #
Version using nested lift calls.
Interacts with the console and stores the last answer in state.
>>>:t runStateT (runExceptT weird) "init"runStateT (runExceptT weird) "init" :: IO (Either Int Double, String)