Scala の Collection っぽいなにか in Python
パクってみたシリーズもう一つ。
Scala の Collection は、collection に対する処理をテンポ良く書けるインタフェイスなので結構好きである。
例えば以下のように
scala> 1 to 10 filter(_ % 2 == 0) map(_ * 30) res1: scala.collection.immutable.IndexedSeq[Int] = Vector(60, 120, 180, 240, 300)
やりたいことをメソッドチェインで繋いで書いていけるので、あれやってこれやってと処理の並びで書ける。
そこいくと Python は
>>> map(lambda x:x * 30, filter(lambda x: x % 2 == 0, range(1, 11))) [60, 120, 180, 240, 300]
となっていて、 filter して map して、という手順と記述が逆なのでちょっと思考の妨げになる。
内包表記を使ってもあんまり変わらない気がする。
>>> [x * 30 for x in range(1, 11) if x % 2 == 0] [60, 120, 180, 240, 300]
そんなわけで Scala の Collection みたいなインタフェイスを持った Python の iterable が欲しいなーと思っていたので作ってみた。
scala like collection
とりあえず ここらへん に置いてある。
とりあえず使ってみる。
>>> from scalalike.collections import collection >>> it = collection.Iterable(range(1, 11)) >>> it.filter(lambda x:x % 2 == 0).map(lambda x:x*30).to_list() [60, 120, 180, 240, 300]
何となくそれっぽくなりました。
pyexpression
ここでさらに これ で作った boost.lambda もどきを使うと
>>> from scalalike.collections import collection >>> from pyexpression import _ >>> it = collection.Iterable(range(1, 11)) >>> it.filter(_ % 2 == 0).map(_*30).to_list() [60, 120, 180, 240, 300]
とか書けるわけですね。
ほら Scala っぽいでしょう?
っていう俺得ライブラリでした。
こういうのは PyPI とかに上げたほうがいいのかなーと思いつつやってない。今度やろう。