swizec.com

#### Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Learn more

# 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-1yb0ye3{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-1yb0ye3 .comment,.css-1yb0ye3 .prolog,.css-1yb0ye3 .doctype,.css-1yb0ye3 .cdata,.css-1yb0ye3 .punctuation{color:#b6ad9a;}.css-1yb0ye3 .namespace{opacity:0.7;}.css-1yb0ye3 .tag,.css-1yb0ye3 .operator,.css-1yb0ye3 .number{color:#063289;}.css-1yb0ye3 .property,.css-1yb0ye3 .function{color:#b29762;}.css-1yb0ye3 .tag-id,.css-1yb0ye3 .selector,.css-1yb0ye3 .atrule-id{color:#2d2006;}.css-1yb0ye3 .attr-name{color:#896724;}.css-1yb0ye3 .boolean,.css-1yb0ye3 .string,.css-1yb0ye3 .entity,.css-1yb0ye3 .url,.css-1yb0ye3 .attr-value,.css-1yb0ye3 .keyword,.css-1yb0ye3 .control,.css-1yb0ye3 .directive,.css-1yb0ye3 .unit,.css-1yb0ye3 .statement,.css-1yb0ye3 .regex,.css-1yb0ye3 .at-rule{color:#728fcb;}.css-1yb0ye3 .placeholder,.css-1yb0ye3 .variable{color:#93abdc;}.css-1yb0ye3 .deleted{text-decoration-line:line-through;}.css-1yb0ye3 .inserted{text-decoration-line:underline;}.css-1yb0ye3 .italic{font-style:italic;}.css-1yb0ye3 .important,.css-1yb0ye3 .bold{font-weight:700;}.css-1yb0ye3 .important{color:#896724;}.css-1yb0ye3 .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}```(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.

## Haskell

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

#### Continue reading about Crowdsourcing elegance

Semantically similar articles hand-picked by GPT-4

### Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Learn more

Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

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

Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

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 by Swizec with ❤️