21Mar

Coffeescript deconstruction of arrays

Posted by Elf Sternberg as javascript

Most people who’ve been using Coffeescript for the past year are probably aware by now of argument deconstruction for objects. ┬áThis is a nifty feature of Coffeescript that lets us take this:

myfunc = (options) ->
    @foo = options.foo
    @bar = options.bar
    ...

And instead say this:

myfunc = ({@foo, @bar}) ->
    ...

In both cases, foo and bar will automagically be bound to the this operator and set to the corresponding values in the options object, if they exist.

A couple of weeks ago I posted Coffeescript is a gateway drug to Haskell, which showed how the quicksort algorithm as apparent in Haskell could almost completely be reproduced in Coffeescript. The Haskell function looked like this:

quicksort [] = []
quicksort (x:xs) =
       let smallerOrEqual = [a | a  x]
       in quicksort smallerOrEqual ++ [x] ++ quicksort larger

My function was a little uglier; I was disassembling the array into car and cdr components in the function, my comprehensions weren’t lazy, and the pattern had to be moved into the function as a guard condition.

Linus Thiel and I had a couple of go-rounds on this, and he taught me something fascinating, and at the end, this is what we had:

quicksort = ([x, xs...]) ->
    return [] unless x?
    smallerOrEqual = -> (a for a in xs when a <= x)
    larger = -> (a for a in xs when a > x)
    (quicksort smallerOrEqual()).concat(x).concat(quicksort larger())

The guard condition is still there, but it’s much more readable. I made the list comprehensions lazy. But Linus showed me how the deconstruction operator for Coffeescript can be used to achieve car:cdr effectively in Coffeescript, and that just blows my mind, because now it means that yet another common transformation is part of my toolkit.

Coffeescript continues to amaze me as it grows and matures into a full-fledged language.  The more I work with it, the more I realize I may not write in raw Javascript ever again if I can avoid it.

1 Response to Coffeescript deconstruction of arrays

A Sip of CoffeeScript | prose :: and :: conz

August 14th, 2013 at 7:02 am

[…] of a Java varargs. By itself, it’s no big deal. The cool factor is in how it can be used for list deconstruction. This allowed me to do some recursive handling of a list I had in my code. A recursive summation of […]

Comment Form

Subscribe to Feed

Categories

Calendar

March 2012
M T W T F S S
« Feb   Apr »
 1234
567891011
12131415161718
19202122232425
262728293031