# [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.

Thanks.

Michael

--- 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>
Date: Saturday, April 18, 2009, 2:36 PM

Michael,

> 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
always
equality...

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
careful.

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

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.
Functions
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.

Regards,
John

-------------- next part --------------
An HTML attachment was scrubbed...
```