5 ms·
I recognize destructuring from Clojure. Did it origniate there? Or is this a specific case of pattern matching?
by thomasvarney723 11y ago
I recognize destructuring from Clojure. Did it origniate there? Or is this a specific case of pattern matching?
- nahiluhmot 11y agoCommon Lisp also has destructuring-bind[0], although its not provided with every implementation. [0] https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node252.html https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node252.html
- bshimmin 11y agoOther languages have this too, eg. Ruby: a, b = [1, 2] a, b = {:a => 1, :b => 2} Similarly in Python, at least for the array example (there's probably some way of destructuring a dictionary in Python, but I don't know it myself). PHP also has `list()`...
- petepete 11y agoFor arrays, yes, but that won't work for Ruby hashes (which aren't ordered): [1] pry ~ » a, b = {a: 1, b: 2} { :a => 1, :b => 2 } [2] pry ~ » a { :a => 1, :b => 2 } [3] pry ~ » b nil
- bshimmin 11y agoYou're quite right, I meant to add `values_at` in the hash example! And the syntax is still not so nice: irb(main):005:0> a, b = {:a => 1, :b => 2}.values_at(:a, :b) => [1, 2] Or: irb(main):006:0> a, b = (h = {:a => 1, :b => 2}).values_at(*h.keys) => [1, 2] Edit: Ruby's hashes are ordered since 1.9, incidentally.
- petepete 11y agoa, b = {a: 1, b: 2}.values
- nbouscal 11y agoIt's basically just pattern matching. Similar things have been around since at least the 70s (e.g. in SASL).
- btbuildem 11y agoErlang and Python have destructuring as well - it's a pretty established shorthand.