Image by ijiwaru jimbo via Flickr

On Friday I said that Functional isn’t always better, but really it was a post about my failings as a functional programmer in finding an elegant solution to the problem of transforming a list of values into a list of pairs.

Originally I described the problem like so:

The problem is one of turning a list of values, say, [A, B, C, D] into a list of pairs with itself, like so [[A,B], [A,C], [A,D], [B, C], [B,D], [C,D]].

Should be simple enough right? You just make another list shifted by one to the left, make a zip, then repeat until the second list is empty. This solution turns out to be horrible, looks ugly and I’m not even going to show it. So here’s my second functional solution … it’s a lot cleaner.

Turns out the internet is super awesome and was more than willing to put me in my place. You guys posted a cumulative of 49 comments (on hackernews and this blog) and Brian Marick even posted a tutorial on approaching functional programming on this example, entitled Top-down design in “functional classic” programming.

Solutions were posted in Clojure, Haskell, Python, J, Scala, Javascript, Erlang, SmallTalk, C#, Ocaml, F#, … and some language I didn’t recognize nor did the poster specify what it was.

## Clojure

They ranged from painfully obvious (@sbelak)

`(combinations '[a b c d] 2)`

A saner (only core) solution in Clojure supposedly looks like this

```(defn tails [xs] (take-while not-empty (iterate rest xs)))   (defn pairs [xs] (mapcat (partial map vector) (map repeat xs) (rest (tails xs))))```

## J

To what the fuck am I looking at (I think this is J)

```a = 'abcd'   comb=: 4 : 0 k=. i.&gt;:d=.y-x z=. (d\$ ,&amp;.&gt;/\. &gt;:&amp;.&gt; z end. ; z )   (2 comb #a) { a```

Most people seem to have given it a shot in either Clojure or Haskell, meaning that I need to look up both of those languages a whole lot more.

This is my favourite Haskell solution, by @purzelrakete

`[[x, y] | x &lt;- set, y &lt;- set, x &lt; y]/pre&gt;`

## Javascript

A really cool Javascript solution by Shaun Gilchrist.

```function pairs(set) { return _.isEmpty(set) ? [] : _.map(_.rest(set), function(y){ return [_.first(set), y]}) .concat(pairs(_.rest(set))); }```

## C#

For some reason I didn’t think C# would even make it to such a debate, but Strilanc makes it quite elegant.

`list.SelectMany((e, i) =&gt; list.Skip(i+1).Select(f =&gt; Tuple.Create(e, f)))`

## Python

Here’s a nice succint solution in Python

`[(x[i],x[j]) for i in range(len(x)) for j in range(i+1, len(x))]`

## Ocaml

And Ocaml by the same guy (fab13n)

```let rec pairs = function | a :: b -&gt; List.map (fun x -&gt; (a, x)) b @ (pairs b) | [] -&gt; []```

## F#

According to @demisbellot it would look like this in F#

```let rec pairs = function | h :: t -&gt; List.append [ for i in t -&gt; [h; i] ] (pairs t) | _ -&gt; []   ["A"; "B"; "C"; "D"] |&gt; pairs```

## Scala

Scala by XxXX

``` def pair(l : List[String]): List[Tuple2[String, String]] = l.size match { case 1 =&gt; Nil case _ =&gt; l.tail.flatMap { e =&gt; List((l.head, e)) } ++ pair(l.tail) }```

## Erlang

By JoelPM … although I’m not sure this is elegant.

```-module(combos).   -export([ combo/1 ]).   combo(List) -&gt; combo(List,[]).   combo([],Acc) -&gt; lists:reverse(Acc); combo([H|T], Acc) -&gt; combo(T,permute(H,T,Acc)).   permute(X,[],Acc) -&gt; Acc; permute(X,[H|T],Acc) -&gt; permute(X,T,[{X,H}|Acc]). Output: 1&gt; combos:combo([a,b,c,d]).[{a,d},{a,c},{a,b},{b,d},{b,c},{c,d}]2&gt;```

## More javascript

@refaktor gave it the most attempts … I think he had a boring weekend, or just got nerd sniped. Here’s his his final solution in javascript … would have expected rebol from him though.

`var f = function(a) { return a.length == 0 ? [] : (a.slice(1).map(function(x){return [a[0],x]})).concat(f(a.slice(1))); }`

## Smalltalk

By Larry … he didn’t leave a link.

`in := #(a b c d) asOrderedCollection.out := OrderedCollection new.in size timesRepeat: [ key := in removeFirst. in do: [ :value | out add:( Array with: key with: value). ].].`

## Conclusion

There were other good solutions, but I think these are the most interesting to look at. This whole experience proves that sometimes when you ask for help on the internets Good Things ™ happen.

It also proves that geeks love outdoing each other.

### Learned something new? Want to improve your skills?

Join over 10,000 engineers just like you already improving their skills!

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

PS: You should also follow me on twitter 👉 here.
It's where I go to shoot the shit about programming.