[Haskell-cafe] General function to count list elements?

nowgate at yahoo.com nowgate at yahoo.com
Sat Apr 18 15:30:26 EDT 2009

Hi John,

Yes, I see now what the hullabaloo was about.

I've only been hacking Haskell for a few weeks, so I'm still seeing the "forest" rather than the "trees". But I'm coming along.



--- On Sat, 4/18/09, John Dorsey <haskell at colquitt.org> wrote:

From: John Dorsey <haskell at colquitt.org>
Subject: Re: [Haskell-cafe] General function to count list elements?
To: "michael rice" <nowgate at yahoo.com>
Cc: haskell-cafe at haskell.org
Date: Saturday, April 18, 2009, 2:36 PM


> I had a count function that worked fine for an enum type, but thought
> why not go polymorphic with it. So I changed it and got the error I
> originally inquired about.

For variety, I'll go a slightly different direction.

If you generalize count to use any predicate, instead of

    gcount :: (a -> a -> Bool) -> a -> [a] -> Int
    gcount pred x0 xs = length (filter (pred x0) xs)

    count = gcount (==)

This will work with any type that you can write a predicate for with the
type (a -> a -> Bool).  I can even use this with functions, if I'm

    ghci> gcount (\f g -> True)       (*2) [id,(const 1),(*3)]
    ghci> gcount (\f g -> f 1 == g 1) (^2) [id,(const 1),(*3)]

By the way, do you see why everyone's bothing you about comparing
functions?  The type you gave count, which didn't have an Eq constraint,
was an assertion that you could compare two values of *any* type.  If
there's a type that's not comparable, then count's type was wrong.
 are the canonical example of an incomparable type.

When you're bored some time, read a bit about the Curry-Howard
correspondence.  It's interesting, even if (like me) you don't grok all
of its implications.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090418/a0e460a3/attachment.htm

More information about the Haskell-Cafe mailing list