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

Kaoru Hosokawa khosokawa at gmail.com
Sat Mar 12 00:47:12 EST 2005


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

This is my solution. I give it here, since it's not an elegant solution.

	howManyOfFourEqual :: Int -> Int -> Int -> Int -> Int
	howManyOfFourEqual a b c d
			| a == b && howManyEqual b c d /= 0	= howManyEqual b c d + 1
			| a == c && howManyEqual b c d /= 0	= howManyEqual b c d + 1
		   	| a == d && howManyEqual b c d /= 0	= howManyEqual b c d + 1
		   	| a == b && howManyEqual b c d == 0	= 2
		   	| a == c && howManyEqual b c d == 0	= 2
		   	| a == d && howManyEqual b c d == 0	= 2
		   	| otherwise						= howManyEqual b c d

howManyEqual is a function from a previous exercise.

	howManyEqual :: Int -> Int -> Int -> Int
	howManyEqual a b c
	     	| a == b && b == c				= 3
	     	| a /= b && b /= c && a /= c	= 0
	     	| otherwise      	     		= 2

I hope to find a better solution. I googled but couldn't find the 
answer.

Kaoru Hosokawa
khosokawa at gmail.com



More information about the Haskell-Cafe mailing list