1. 6
  1.  

  2. 2

    At first glance, I thought that list_to_tuple(?CHARS) would be called with every invocation of slug:new/1. After looking at the optimized assembler code, I’m happy to see that I was wrong! In fact, literals for both Cs and CsLen are moved into the code for executing the list comprehension.

    A quote attributed to Joe Armstrong is “Make it work, then make it beautiful, then if you really, really have to, make it fast.” Turns out this code, which I find to be pretty elegant, is compiled down to basically optimal BEAM bytecode.

    1. 2

      So, the code is creating a list of N elements by picking them out of a given list. I have to point out though that I am not fluent in erlang, so I probably missed the point. Can someone point me to the inherent beauty? While this surely is compact code, I keep looking for its cleverness.

      1. 1

        I think part of the point is that you accurately described what the code does despite your not being fluent in Erlang. There are a couple of nice things (in my opinion) about the language and the implementation:

        1. The ‘given list’ ?CHARS is converted from a list to a tuple. Tuples in Erlang have O(1) lookup, with the trade-off that they’re expensive to update. In this case, using a tuple makes a lot of sense.
        2. The values of Cs and CsLen are calculated at compile-time, so, despite appearances, they don’t wind up being recalculated for every call to new/1. This means you don’t have to compromise between efficiency and keeping ?CHARS looking clean.
        3. Strings are plain lists in Erlang. That final list comprehension returns a valid string; no conversion is needed.