I tend to write rather functional code in Python so when I switch to Clojure I don't have to learn lots of things. Yet I often forget how to express some concepts in Clojure.
itertools.count(0)
becomes (iterate inc 0)
range(1, 10, 2)
becomes (range 1 10 2)
. So obvious that I don't expect it.
for x in ...: body
becomes (for [x ...] body)
. Actually, this is more like a generator expression and is way more powerful. But that's the simple case.
I don't know a direct Python version in the Stdlib, but clojure.contrib.seq.separate
is a useful solution in Clojure.
To read files line-wise, like popular in Python by iterating over file objects, clojure.contrib.duck-streams.read-lines
can be used, which returns a line Seq.
In Python the extend
method can be used. Clojure has a nice merge-with
function, to merge data structures.
Clojures reduce
is quirky, behaves a bit differently depending on how many arguments you specify. Might be worth a look.
Both Clojure and Python have partial
, use it.
In Python there are libraries for this, Clojure comes directly with a comp
function that can be used to compose multiple functions.
In Python there is operator.attrgetter
to get an attribute from an object. In Clojure the key names :keyname
can be used directly as accessor functions.
It's dict.update, not dict.extend. And sadly there's no immutable version.