Hacker News new | ask | show | jobs
by seanhunter 1385 days ago
python has a built-in filter() that works exactly as your List.filter does. It's possible Peter Norvig just prefers list comprehensions, but it's not a weakness of the language or whether the Python community embraces filters per se.

     filter(lambda x: x in WORDS, words)
would I think do pretty much the same as what he wrote, and then depending on how you use the output, you may want to wrap that in list() or something. If you are going to iterate over it, it's gtg as-is.

There are much more idiomatic and clear (imo) ways of definining a function-static block (which gets evaluated just the first-time a function is called) than that default arg trick.

2 comments

Yea, I know about Python's filter, but it seems not really used much (because it needs piping to be really useful). I used F# because I didn't want to bother looking up the syntax for Python.

Although, F# has list comprehensions as well.

    [for word in words do if List.contains word WORDS then word]
That's verbose because I spelled out word, but I feel it reads well while the Python version is weird to me. Mathematical set definitions follow the form of {e <- set | <condition on e>} which is read as "e in set such that e satisfies condition" or "for e in set and e satisfies condition". The Python version kind of reads weird to me as it's more like {e | e <- set | <condition on e>}. (I note that Counter is some iterable object and not a list, I suppose.) I really like comprehensions, but I always find Python's to be a bit strange. I think it's because the "in" in the posted comprehension has two semantic meanings, if I understand correctly. It's a nitpick for sure, but slippery is the best way I can describe Python.

> then depending on how you use the output, you may want to wrap that in list() or something

Shudder. Haha.

Yea, the default argument trick threw me off, which is why I don't think it's a good example of the "best" code. The best code doesn't have tricks.

It's a neat domain program, but not the "best" code.

That filter statement gets you an iterator, not a list. The reality is that map and filter in python aren't terribly ergonomic and thus are avoided even given a near-perfect use case, e.g. point-free application.