[Haskell-beginners] Tuples .vs Either Vs datatypes
MAN
elviotoccalino at gmail.com
Tue Apr 5 20:04:30 CEST 2011
I, for one, have a simplified view of the three that often proves
helpful for fast decisions:
- tuples are a sort of quick-and-dirty tool that gets the job done
(simple to code, accessors and constructor already there). They don't
stand well for refactoring and maintenance.
- A simple, custom datatype like yours is more explicit, easier to read
(later, after you wrote the program), and flexible. It requires bit more
code to write, and names (good names, please!) thought out.
- Apart from being a good container, Either has an Monad instance
written for you. It allows data-on-the-side :). This can prove
incredibly valuable in *some* situations. Think through if it's worth it
(it can cripple your code if your not sure about the "shape" data should
take).
I hope I'm expressing clearly enough (this subject borders
subjectivity).
El mar, 05-04-2011 a las 13:41 -0400, Mike Meyer escribió:
> 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.
>
> Thanks,
> <mike
More information about the Beginners
mailing list