swizec.com

## Crowdsourcing elegance

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)

`.css-1baulvz{display:inline-block;}(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.>:d=.y-x z=. (d\$ ,&.>/\. >:&.> 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 <- set, y <- set, x < y]/pre>`

## 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) => list.Skip(i+1).Select(f => 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 -> List.map (fun x -> (a, x)) b @ (pairs b)    | [] -> []`

## F

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

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

## Scala

Scala by XxXX

`def pair(l : List[String]): List[Tuple2[String, String]] = l.size match { case 1 => Nil case _ => l.tail.flatMap { e => 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) ->  combo(List,[]).combo([],Acc) ->  lists:reverse(Acc);combo([H|T], Acc) ->  combo(T,permute(H,T,Acc)).permute(X,[],Acc) ->  Acc;permute(X,[H|T],Acc) ->  permute(X,T,[{X,H}|Acc]).Output:1> combos:combo([a,b,c,d]).[{a,d},{a,c},{a,b},{b,d},{b,c},{c,d}]2>`

## 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 (tm) happen.

It also proves that geeks love outdoing each other.

Published on October 10th, 2011 in Uncategorized

## Learned something new? Want to become a high value JavaScript expert?

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.

### Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

Created bySwizecwith ❤️swizec.com