Monadic Parsers using Haskell

An introduction

Tony Morris

Abstract

A hands-on introductory tutorial to monadic parsers using the Haskell Programming Language http://haskell.org/. Students will require an installation of the Glasgow Haskell Compiler http://haskell.org/ghc and a text editor. Upon completion of the tutorial students will have created a parser library.

Students will be expected to have a basic understanding of Haskell syntax and familiarity with tools -- in particular, the GHC interpreter (GHCi).

This document is released under a Creative Commons - Attribution, Non-Commercial, No Derivative Works licence. Appendix D, Licence


Table of Contents

Get Started
What is a Parser?
A data structure
Errors?
Our First Parser
value
Experiment
Failing Parser
Character Parser
character
Experiment
Choice Parser
|||
Experiment
Mapping Parser
mapParser
Experiment
Binding Parser
bindParser
Experiment
>>>
Sequencing Parser
sequenceParser
Experiment
Sequence N Parser
thisMany
Zero or Many Parser
list / many1
Experiment
Satisfy
satisfy
Experiment
Satisfiers
satisfy
Experiment
Introspection
Bits and Pieces
Person
ageParser
firstNameParser
surnameParser
genderParser
phoneBodyParser
phoneParser
Person Parser
Experiment
personParser
Experiment
Bind/Map
bindParser/mapParser
You Bet
Then?
Conclusion
A. MyParser.hs
B. MyParser.scala
C. MyParser.java
D. Licence

Get Started

Let us start by creating a file called MyParser.hs. Then in that file the contents:

module MyParser where

import Data.Char

Start the GHC interpreter ghci and load the source file.

$ ghci
GHCi, version 6.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> :load MyParser.hs
[1 of 1] Compiling MyParser         ( MyParser.hs, interpreted )
Ok, modules loaded: MyParser.
*MyParser>