← Writing

Parser Combinator in Haskell vs. Regex in Python

This isn’t a fair fight. Parser combinators are strictly more powerful than regular expressions — even though plenty of regexes in production pretend otherwise. (If you haven’t read this Hacker News classic about an adventure in regex land, go read it.)

In practice, though, ergonomics matter. Python’s re module is built in and dead simple, while Python parser libraries like PLY or PyParsing feel like overkill for small jobs. Haskell is the exact opposite: Parsec is stupidly easy to reach for, whereas I’ve never managed to do anything in Haskell regex beyond trivial matching (noob alert, duh).

So let’s pit them against the same tiny problem: parse a 12-hour time string like "11:00:00AM" (where the separator can be :, /, or -) into a struct holding hour, minute, second, and period (AM/PM).

Round 1: Python + Regex

import re
from collections import namedtuple

Time = namedtuple('Time', ['hh', 'mm', 'ss', 'period'])

time_digits = r"\d+"
periods = "AM|PM"
separators = "[:/-]"
pattern = re.compile(r"({digits}){sep}({digits}){sep}({digits})({periods})".format(
    digits=time_digits, sep=separators, periods=periods))
# or as a one-liner: re.compile(r"(\d+)[:/-](\d+)[:/-](\d+)(AM|PM)")

timeParser = lambda input: Time(*pattern.match(input).groups())

Let’s poke it:

timeParser("11:00:00AM")
# Time(hh='11', mm='00', ss='00', period='AM')

timeParser("99:99:99AM")
# Time(hh='99', mm='99', ss='99', period='AM')

timeParser("11.00.00AM")
# AttributeError: 'NoneType' object has no attribute 'groups'

It works, with three classic annoyances:

  1. Everything comes back as strings, so you still have to cast '11' to 11 afterwards.
  2. It happily accepts 99 o’clock.
  3. When the input fails, re just shrugs and hands you None, leaving your lambda to crash with AttributeError and zero clue where things went wrong.

Round 2: Haskell + Parsec

import Text.ParserCombinators.Parsec
import Control.Monad

data Time = Time Int Int Int String

timeParser = Time <$> (digits <* sep) <*> (digits <* sep) <*> digits <*> period
    where digits = liftM read $ many1 digit
          period = choice [string "AM", string "PM"]
          sep    = oneOf ":/-"

If you don’t read Haskell, that one-liner looks like someone dropped a keyboard down the stairs, so here’s the decoder ring:

  • digits, period, and sep are three tiny parsers, each doing one job.
  • digits <* sep means “parse digits, then parse sep, and throw sep away.”
  • Time <$> a <*> b <*> c <*> d means “run those four parsers in order and pass their results into Time.”

Notice digits ends with read, so by the time you get a Time back, hour, minute, and second are already Ints. Parsing and type conversion happen together.

Both versions are slick in their own way (argument unpacking in Python, applicative style in Haskell). Where parser combinators really pull ahead is when the requirements stop being cute. And you don’t even need to install Haskell to see why — we can just steal the idea in Python.

Stealing parser combinators for Python

The whole secret of parser combinators is absurdly simple: a parser is just a function. Give it (text, pos) and it either returns (value, new_pos) or raises an error. A combinator is just a function that glues small parsers into bigger ones.

Seven tiny functions is all it takes:

class ParseError(Exception):
    pass

def one_of(chars):
    def parse(text, pos):
        if pos < len(text) and text[pos] in chars:
            return text[pos], pos + 1
        raise ParseError(f"expected one of {chars!r} at position {pos}")
    return parse

def string(s):
    def parse(text, pos):
        if text.startswith(s, pos):
            return s, pos + len(s)
        raise ParseError(f"expected {s!r} at position {pos}")
    return parse

def many1(parser):  # one or more
    def parse(text, pos):
        value, pos = parser(text, pos)
        values = [value]
        while True:
            try:
                value, pos = parser(text, pos)
            except ParseError:
                return values, pos
            values.append(value)
    return parse

def choice(*parsers):  # first one that works
    def parse(text, pos):
        for parser in parsers:
            try:
                return parser(text, pos)
            except ParseError:
                pass
        raise ParseError(f"nothing matched at position {pos}")
    return parse

def seq(*parsers):  # one after another
    def parse(text, pos):
        values = []
        for parser in parsers:
            value, pos = parser(text, pos)
            values.append(value)
        return values, pos
    return parse

def fmap(f, parser):  # Haskell's <$>
    def parse(text, pos):
        value, pos = parser(text, pos)
        return f(value), pos
    return parse

def left(a, b):  # Haskell's <*
    return fmap(lambda pair: pair[0], seq(a, b))

Now the Haskell version translates into Python almost word for word:

digits = fmap(lambda ds: int("".join(ds)), many1(one_of("0123456789")))
sep    = one_of(":/-")
period = choice(string("AM"), string("PM"))

time_parser = fmap(lambda v: Time(*v), seq(left(digits, sep), left(digits, sep), digits, period))

time_parser("11:00:00AM", 0)
# (Time(hh=11, mm=0, ss=0, period='AM'), 10)

time_parser("11.00.00AM", 0)
# ParseError: expected one of ':/-' at position 2

Not as pretty as Haskell’s operators, sure, but look what we got for free: real integers, and error messages that actually tell you what went wrong and at which character.

Now fix 99 o’clock

In regex, teaching it to count from 1 to 12 means spelling out character-by-character arithmetic:

pattern = re.compile(r"(0?[1-9]|1[0-2])[:/-]([0-5]?\d)[:/-]([0-5]?\d)(AM|PM)")

It works, and I had to squint at it three times to be sure — and I’m the one who wrote it.

With combinators, you add one helper and write the rule like a normal human being:

def check(parser, is_valid, what):
    def parse(text, pos):
        value, new_pos = parser(text, pos)
        if not is_valid(value):
            raise ParseError(f"{value} is not a valid {what} at position {pos}")
        return value, new_pos
    return parse

hour   = check(digits, lambda h: 1 <= h <= 12, "hour")
minute = check(digits, lambda m: m < 60, "minute")
second = check(digits, lambda s: s < 60, "second")

time_parser = fmap(lambda v: Time(*v), seq(left(hour, sep), left(minute, sep), second, period))

time_parser("99:99:99AM", 0)
# ParseError: 99 is not a valid hour at position 0

time_parser("11:75:00AM", 0)
# ParseError: 75 is not a valid minute at position 3

Every piece has a name, every piece is unit-testable on its own, and the rule for an hour is literally 1 <= h <= 12.

Where regex taps out completely

Regex could still limp along for 99 o’clock. Where it hits a brick wall is nesting — say, lists inside lists like [1,[2,[3,4]],[]].

To parse arbitrary nesting, a rule has to call itself, and Python’s re module simply can’t do recursion. For parser combinators it’s trivial, because parsers are just functions and functions call themselves all day long:

def lazy(get_parser):  # lets a parser refer to itself
    return lambda text, pos: get_parser()(text, pos)

def sep_by(parser, separator):  # zero or more, separated by something
    def parse(text, pos):
        values = []
        try:
            value, pos = parser(text, pos)
        except ParseError:
            return values, pos
        values.append(value)
        while True:
            try:
                _, after_sep = separator(text, pos)
                value, pos = parser(text, after_sep)
            except ParseError:
                return values, pos
            values.append(value)
    return parse

def between(opening, parser, closing):
    return fmap(lambda v: v[1], seq(opening, parser, closing))

value  = choice(digits, lazy(lambda: nested))
nested = between(string("["), sep_by(value, string(",")), string("]"))

nested("[1,[2,[3,4]],[]]", 0)
# ([1, [2, [3, 4]], []], 16)

Read those two lines aloud: a value is a number or a nested list, and a nested list is comma-separated values between [ and ]. That’s it.

Don’t throw away your regexes — for quick one-off matching, Python’s re is still hard to beat. Just keep an eye out for the moment you start counting brackets inside a regex. That’s your cue to switch.