1. I'm unfamiliar with the term 'unpacking'. Is it any different from pattern matching in, say, Haskell (but perhaps not as feature-rich)?
2. Aren't slices pretty much a staple in Python? I didn't think using them was considered a 'trick'.
1. I'm unfamiliar with the term 'unpacking'. Is it any different from pattern matching in, say, Haskell (but perhaps not as feature-rich)?
2. Aren't slices pretty much a staple in Python? I didn't think using them was considered a 'trick'.
unpacking < destructuring < pattern matching < first-class patterns
where first-class patterns are increasingly becoming available in some languages which offer pattern matching (in particular, Haskell will have them soon).That's the haskell extension.
To see a very nice use of them, check out this paper (pdf) http://strictlypositive.org/CJ.pdf
I spoke too eagerly—the new feature is just named and namespaced patterns. It's a bit of a bump in power, but it's not fully general yet.
For true(-ish) first-class patterns take a look at Prisms in the lens package or some of the other first-class pattern libraries.
a,(b,c),d = [1,[2,3],4]I think that Python's unpacking allows most, if not all, of Clojures sequence destructuring for tuples and lists. Clojure takes it a bit further, however, by applying it to all sequences. For example, you could do this:
a,b,c = "XYZ"
because strings are also sequences. You can also do something like this (excuse the awkward syntax as I try to express it in pseudo-Python): a,b : c as d = [1,2,3,4,5]
# a = 1
# b = 2
# c = [3, 4, 5]
# d = [1, 2, 3, 4, 5]
This might not be so useful in python, since the list already is d and c is simply slicing the end from the list, but Clojure allows you to destructure function arguments: (defn foo [[a, b & c :as d]] ...) when passed the above list (foo [1 2 3 4 5]) would bind the variables as shown in the above comments.Where destructuring really shines, though, is that you can destructure maps (dictionaries in Python) and vectors can also be treated as maps (their keys are the indices), so you can do stuff like this:
a, {[b {:keys [c, d]} :foo}, e = [1, {foo: [2, {c: 3, d: 4}, bar: 9}, 5]
# a = 1
# b = 2
# c = 3
# d = 4
# e = 5
http://clojure.org/special_forms#binding-forms t = (1, 2)
a, b = t
# a == 1 and b == 2
Using slices is normal with lists php > $t = array(1, 2);
php > list($a, $b) = $t;
php > echo "$a, $b";
1, 2