[Haskell-beginners] Comments on Map/Reduce Code

Brent Yorgey byorgey at seas.upenn.edu
Sun Jul 15 02:35:44 CEST 2012

On Fri, Jul 13, 2012 at 06:02:02PM +0200, Thomas Bach wrote:
> Hi Brent,
> thanks for your suggestions. I got further suggestions as a private
> e-mail and finally came up with the following solution – suggestions
> welcome:

Looks good!

> The reducer still throws an error when piping in an empty
> newline. But, I'm not sure, what a proper solution for this could be.

The problem is your 'summation' function:

  summation :: Num b => [(a, b)] -> (a, b)

In fact, it is impossible to implement something with this type which
works for all inputs.  If you get the empty list as input, there is no
way to make up a value of type 'a' in the output tuple.

Now, if you happen to know a more concrete type for 'a' then you can
do it by using some sort of default value.  For example, in your case
it looks like 'a' will actually be TL.Text.  So you could write

  summation :: Num b => [(TL.Text, b)] -> (TL.Text, b)

by doing something like returning the empty string along with 0 in the
case that the input list is empty.

In this particular case it is probably not that big of a deal.  It is
just good practice to try to always write *total* functions, that is,
functions which give a sensible result (i.e. do not crash) for every
possible input.  This means doing things like (1) make sure you have
covered every possible case when pattern-matching; (2) do not use
functions which can crash like 'head' or 'tail' (use pattern-matching

> On Tue, Jul 10, 2012 at 10:19:48AM -0400, Brent Yorgey wrote:
> > On Thu, Jul 05, 2012 at 03:50:32PM +0200, Thomas Bach wrote:
> > 
> > Instead of using a chain of ($), it's generally considered better
> > style to use a chain of (.) with a single $ at the end, like
> I often find myself trying different combinations of ($), (.) or
> putting things in brackets, when the compiler throws an error on
> me. Without really knowing why things sometimes work out and sometimes
> don't. I find this part especially confusing!

This can be confusing at first.  The solution is (1) make sure you
understand how parsing/operator precedence work, and (2) think hard
about the types of operators like ($) and (.), and what any type
errors are telling you.  You really will not learn much by just
randomly trying to insert ($), (.) or parentheses.


More information about the Beginners mailing list