gkz / prelude-ls

prelude.ls is a functionally oriented utility library - powerful and flexible, almost all of functions are curried. It is written in, and is the recommended base library for, http://livescript.net
http://preludels.com/
MIT License
424 stars 59 forks source link

Nice to have function - transpose #91

Open chrisvfritz opened 9 years ago

chrisvfritz commented 9 years ago

The use case for this is rarer, but it's in Haskell and I do sometimes need it. When I do, it's just on the server side, so this is what I've been using:

transpose = (array) ->
  Object.keys(array[0])
    |> map (column) ->
       array |> map (row) -> row[column]

Since Object.keys isn't supported in <IE9 (I think that's the one), we'd probably need a more lengthy implementation.

igl commented 9 years ago

There is no need for Object.keys to loop over array indices at all.

transpose = (array) ->
    for _, column in array[0]
        for row in array
            row[column]

Maybe zip-all is all you need anyway?

chrisvfritz commented 9 years ago

zip-all could actually do the job here, with zip-all ...array. I still think it'd be great to have transpose as an alias for zip-all ...array though. Not only would it be more natural for folks coming from other functional languages, but let's take the example of piping. Sure, you could do this:

array |> -> zip-all ...it

But it'd be so much cleaner and obvious if I could just write array |> transpose.