Re:Functional isn't always better
by reirob on Friday October 07, 2011 @11:43AM
(#3084429)
Maybe it come from the fact that you are using a non-functional language for functional stuff? In Haskell I'd do it like this:
Tried, out in console:
It seems to do what is supposed to.
[ Parent
| on HN ]
And yet another short, functional solution:
pairs = (>>= \ ~(x:xs) -> map ((,) x) xs) . init . tails
EDIT: Or as a list comprehension: pairs xs = concat [map ((,) h) t | (h:t) <- tails xs]Haskell even has sugar for this via list comprehensions:
Prelude> let pairs = "ABCD"
Prelude> [(x, y) | x <- pairs, y <- pairs, x < y]
[('A','B'),('A','C'),('A','D'),('B','C'),('B','D'),('C','D')]This generates the Cartesian product and filters. (x,y) where both x and y are drawn from the original list. The previous solution only generates pairs (x, y) where y is drawn from elements after x.