[Haskell-cafe] Solution to Thompson's Exercise 4.4

Andy Georges andy.georges at elis.ugent.be
Sat Mar 12 02:29:24 EST 2005


Hi Kaoru,

> I have been working through the exercises in Thompson's The Craft of
> Functional Programming 2nd Ed book. I am looking for a solution web
> site for Thompson's book. Or maybe the people here can help.
>
> In exercise 4.4, I am asked to define a function
>
>  howManyOfFourEqual :: Int -> Int -> Int -> Int -> Int
>
> which returns the number of integers that are equal to each other. For
> example,
>
>  howManyOfFourEqual 1 1 1 1 = 4
>  howManyOfFourEqual 1 2 3 1 = 2
>  howManyOfFourEqual 1 2 3 4 = 0

A solution which is applicable to any number of arguments is this:

import Data.List
howManyOfFourEqual a b c d = determineMaxEquals [a,b,c,d]

determineMaxEquals :: [a] -> Int
determineMaxEquals ls = head $ reverse $ sort $ map length $ group $ sort ls

Of course, determineMaxEquals is fubar if used on an infinite list.

Regards,
Andy


More information about the Haskell-Cafe mailing list