下面这段代码是一个计算JAVA代码覆盖率的过程简化得到的,对一个原始数据文件的每一行进行格式匹配,符合格式的从中抽取出一些数据做和,然后计算比值。运行没有问题,希望能用函数式风格写出来,我懂一些Erlang, Haskell和Clojure,如果能给出这些语言版本的解法也非常感谢!
from __future__ import division import re datafile = ('abc', 'd>11/23d>34/89d', 'e>25/65e>13/25e', 'f>36/92f>19/76') core_pkgs = ('d', 'f') covered_lines, total_lines, covered_branches, total_branches = 0, 0, 0, 0 for line in datafile: for pkg in core_pkgs: ptn = re.compile('.*'+pkg+'.*'+'>(\d+)/(\d+).*>(\d+)/(\d+).*') match = ptn.match(line) if match is not None: cvln, tlln, cvbh, tlbh = match.groups() covered_lines += int(cvln) total_lines += int(tlln) covered_branches += int(cvbh) total_branches += int(tlbh) print 'Line coverage:', '{:.2%}'.format(covered_lines / total_lines) print 'Branch coverage:', '{:.2%}'.format(covered_branches/total_branches)