Keep on moving

あんまりまとまってないことを書きますよ

関数型言語勉強中。

近頃Scalaの勉強を時間を見つけてやってます。

Scalaスケーラブルプログラミング[コンセプト&コーディング] (Programming in Scala)

Scalaスケーラブルプログラミング[コンセプト&コーディング] (Programming in Scala)


とりあえず3章まで読み終わった。
何となく3章の内容をpythonで書き直してみた。
with,三項演算子、reduceを初めて使って見たけどかなりソースがきれいにかけますね。

from __future__ import with_statement
import sys

lines=[]

with file(sys.argv[0], 'r') as fp:
    for line in fp:
        lines.append(line)

longest_line = reduce(lambda x,y:len(x)>len(y) and x or y,lines)
max_width=len(str(len(longest_line)))

for line in lines:
    num_spaces = max_width - len(str(len(line)))
    padding = " " * num_spaces
    sys.stdout.write(padding + str(len(line))+ " | " + line)

【結果】

38 | from __future__ import with_statement
11 | import sys
 1 | 
 9 | lines=[]
 1 | 
35 | with file(sys.argv[0], 'r') as fp:
20 |     for line in fp:
27 |         lines.append(line)
 1 | 
65 | longest_line = reduce(lambda x,y:len(x)>len(y) and x or y,lines)
38 | max_width=len(str(len(longest_line)))
 1 | 
19 | for line in lines:
49 |     num_spaces = max_width - len(str(len(line)))
31 |     padding = " " * num_spaces
61 |     sys.stdout.write(padding + str(len(line))+ " | " + line)