[Haskell-cafe] General function to count list elements?
John Dorsey
haskell at colquitt.org
Sat Apr 18 14:36:07 EDT 2009
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
More information about the Haskell-Cafe
mailing list