Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

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

Senior Engineer Mindset cover
Learn more

    Crowdsourcing elegance

    soba fest 095

    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.>: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

    Did you enjoy this article?

    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 ❤️