I saw the Cerebrate solve the first Scripting Games challenge: Pairing off. And immediately thought “I can do that in Haskell too”.
So, here it is.
import Data.List
cards = [(1,7),(0,5),(3,7),(2,7),(2,13)]
countpairs [] = 0
countpairs [a] = 0
countpairs (a:as) = length . filter (((snd a)==) . snd) $ as
pairingOff = sum . map countpairs . tails
And that’s that. Alas, the actual competition only takes Perl, VBScript and PowerShell, so I won’t be submitting this.
I also like the following:
import Data.List (sort, group)
cards :: [(Int, Int)]
cards = [(1,7),(0,5),(3,7),(2,7),(2,13)]
pairs :: [(Int, Int)] -> Int
pairs = sum . map ((`choose` 2) . length) . group . sort . map snd
-- | Binomial coefficient
-- http://en.wikipedia.org/wiki/Binomial_coefficient
choose :: (Integral a) => a -> a -> a
n `choose` k | n >= k && k >= 0 = fac n `div` (fac k * fac (n - k))
| otherwise = 0
fac :: (Num t) => t -> t
fac 0 = 1
fac n = n * fac (n-1)
(‘choose’ and ‘fac’ don’t actually belong in this script but should be part of a larger mathematical library.)