Hacker News new | ask | show | jobs
by densh 4655 days ago
Python's unpacking is a poor man's pattern matching. I'd really love to see them extend it to support user-defined patterns like Scala's extractors or F#'s active patterns.
1 comments

I think unpacking is just unpacking, languages that have pattern matching allow you to do something identical:

# let i = (1,2,3) ;;

val i : int * int * int = (1, 2, 3)

# let a,b,c = i;;

val a : int = 1

val b : int = 2

val c : int = 3

Unpacking pretty much does one thing, and it makes that one thing easier and a lot more readable. Combine that with list comprehension (from what I understand C#'s LINQ is similar) and you end up with code that's highly maintainable/readable (as long as you name your variables appropriately, of course).

I believe Python supports pattern matching other than Regex as well.

Python list comprehensions are not lazy, though. If you generate [for x in xrange(1, 10000)] you'll get 10000 elements in your list. My understanding is that LINQ list comprehensions are that.

> I believe Python supports pattern matching other than Regex as well.

That's pattern matching on strings. The kind of pattern matching being discussed here is pattern matching on data types (see [1]).

1: http://en.wikipedia.org/wiki/Pattern_matching

Python does have generator expressions, for instance what you wrote above is written (lazily) as:(x for x in xrange(1, 10000))

It doesnt have functional style pattern matching though.

'Lazy lists' are called generators in Python. Just use (...) Instead of [...] in your example.
I'm aware of generator expressions, but the fact that list comprehensions are not lazy can trip people if they are used to other languages with this feature, since they are usually lazy.
Reading through http://en.wikipedia.org/wiki/List_comprehension, it seems that there are roughly equal numbers of languages where "list comprehension" produces strict list as languages where it produces lazy lists.

I think it's a lack of naming convention - the word "list" on its own means "strict list" in some languages and "lazy list" in others.

I don't agree, people are more likely to come from python that to python from a language that has lazy list comprehensions. But regardless, using a language requires that you learn it and I doubt many people think list comp is lazy. Pythonic programming obeys explicit over implicit, which which if you want a lazy version you explicitly use a lazy version.