[Haskell-beginners] Tuples .vs Either Vs datatypes

Mike Meyer mwm at mired.org
Tue Apr 5 19:41:07 CEST 2011

One of the exercises in Real World Haskell is to write a glob matcher
without translating it to regular expressions. This turns out to be a
lot more subtle than it looks (character classes like [!]-}] tend to
break things).

In doing this, I wrote a matchCharClass function for handling
character classes. The initial version had type:

matchCharClass :: Pattern -> Char -> (Bool, Pattern)

I.e. - it returned rest of pattern after the char class as well as a
match succeed/fail indicator. Upon reflection, I realized that only
one of the two was ever used, so rewrote it to be:

matchCharClass :: Pattern -> Char -> Either Bool Pattern

This made the calling code a little larger - taking a apart tuples is
a bit easier than taking apart Either's - but simplified the values
being generated. I then realized that the code only used one of the
Bool values: if it was True, then Pattern got used instead. So I
rewrote it a third time, giving:

data CharClass = Fail | Pattern String
matchCharClass :: Pattern -> Char -> CharClass

This only required minor changes to the code, but made it easy to add
"Error String" to the CharClass datatype later. That version can be
seen at http://pastebin.com/eyre8795 (as always, critiques welcome).

I'd like to hear what more experienced haskell programmers have to say
about those three ways of returning multiple values.

Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

More information about the Beginners mailing list