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

added fold-obj-to-list #97

Open homam opened 8 years ago

homam commented 8 years ago

fold-obj-to-list can save an extra map:

array
    |> group-by key
    |> obj-to-pairs
    |> map ([k, vs]) -> merge k, vs
array
    |> group-by key
    |> fold-obj-to-list (k, vs) -> merge k, vs

It's defined like:

# (a -> b -> c) -> {a: b} -> [c]
fold-obj-to-list = (f, object) -->
  [f key, value for key, value of object]
anko commented 8 years ago

I'm increasingly worried about "because it saves an extra loop" as a reason to add a new utility function. Should we also have fold-obj-to-list-then-filter because it saves an extra filter? Arbitrary amounts of loop fusion could be done this way (and many like concat-map and partition already exist), but as you demonstrate, they are logically redundant with existing operations.

That said, I've often wanted to fold an object into a list. Consider this a slightly reluctant +1.

Your comment's code blocks call it fold-obj-to-pairs. Those should be fold-obj-to-list right?

homam commented 8 years ago

(group-by f) >> obj-to-pairs >> (map ([k, v]) -> merge k, v) is a very common pattern when dealing with tabular data like the result of SQL queries. I wish LiveScript had a compiler that supported fusion but ...

I think there's a need for an abstract obj-to-pairs: obj-to-pairs = fold-obj-to-list (a, b) -> [a, b]