lantiga / ki

lisp + mori, sweet.js
ki-lang.org
MIT License
478 stars 28 forks source link

Destructuring #11

Open lantiga opened 10 years ago

lantiga commented 10 years ago

Consider introducing destructuring.

fasterthanlime commented 9 years ago

I'm very interested in this feature. How complex do you think it would be to implement in terms of sweet.js macros/rules?

lantiga commented 9 years ago

Got this

(let [[a [b] c [[d e] f]] [1 [2] 3 [[4 5] 6]]]
  (add a b c d e f))
=> 21

working with this 5fd812b0892f3a8d9c9540a7fc1831945a14cb79 commit (works only for nested vector in a let form). It's a start, I'm quite impressed at how little code it took with sweet.js.

lantiga commented 9 years ago

And here's fe371c0c18671295e51823258ac6777ca4db4a41 destructuring of maps (mixed with vectors) in let forms:

(let [{[a] :a b :b} {:a [1] :b 2}]
     [a b])
=> [1 2]

Well, that does it (for mori data structures and literals - we could probably consider adding destructuring with js array and object literals [$ ] {$ }, we'll see about it).

Now I have to figure out how to call the _destr macro in

Anywhere else?

fasterthanlime commented 9 years ago

From [http://clojure.org/special_forms#Special Forms--Binding Forms (Destructuring)](http://clojure.org/special_forms#Special Forms--Binding Forms %28Destructuring%29):

Clojure supports abstract structural binding, often called destructuring, in let binding lists, fn parameter lists, and any macro that expands into a let or fn.

So I think your list had it covered. I have mixed feelings about letc, it's probably really useful for Node.js-style APIs, but does it belong in core? Not that it's expensive to have it there, though.

Destructuring JS arrays/objects sounds interesting (and would actually give ki an edge over vanilla cljs), but probably not high-priority for now :)

lantiga commented 9 years ago

Great, thanks for the quote - somehow it didn't occur to me that I could check on the Clojure website.

I feel the same way as you do about letc. It's possibly a nice to have, but it could indeed belong to an external macro library if we have enough of them at some point.

As for the JS arrays/objects destructuring, I just added it: 6ac7006cc0fabec6f749febd7710b2aed0d997b0

lantiga commented 9 years ago

Added destructuring in loop 16b3051f1d71cf1650ac995fe6ddd758de60b2bd and tests for destructuring so far 06760fafaa390abdae3b144b83b2fe1f57f65e3b.

Adding destructuring to function signatures is harder due to the way sweet tokenizes the arguments. I had a working prototype for 1-arity functions but the thing brake down for n-arity. Needs some more thinking.