我编写了一个小脚本来遍历文件夹中的文件以计算代码行数。
脚本的核心是计算空格、注释和代码行数的函数。 (请注意,目前它是为 C# 量身定制的,不知道多行注释)。
我觉得它看起来不太好 - 谁有更干净的版本?
// from list of strings return tuple with count of (whitespace, comments, code)
let loc (arr:List<string>) =
let innerloc (whitesp, comment, code) (l:string) =
let s = l.Trim([|' ';'\t'|]) // remove leading whitespace
match s with
| "" -> (whitesp + 1, comment, code) //blank lines
| "{" -> (whitesp + 1, comment, code) //opening blocks
| "}" -> (whitesp + 1, comment, code) //closing blocks
| _ when s.StartsWith("#") -> (whitesp + 1, comment, code) //regions
| _ when s.StartsWith("//") -> (whitesp, comment + 1, code) //comments
| _ -> (whitesp, comment, code + 1)
List.fold_left innerloc (0,0,0) arr
最佳答案
我认为您拥有的很好,但这里有一些可以混合使用的品种。 (此解决方案重复了您忽略尾随空格的问题。)
type Line =
| Whitespace = 0
| Comment = 1
| Code = 2
let Classify (l:string) =
let s = l.TrimStart([|' ';'\t'|])
match s with
| "" | "{" | "}" -> Line.Whitespace
| _ when s.StartsWith("#") -> Line.Whitespace
| _ when s.StartsWith("//") -> Line.Comment
| _ -> Line.Code
let Loc (arr:list<_>) =
let sums = Array.create 3 0
arr
|> List.iter (fun line ->
let i = Classify line |> int
sums.[i] <- sums.[i] + 1)
sums
将“分类”作为一个单独的实体在其他情况下可能会有用。
关于c# - 你能在 F# 中改进这个 'lines of code algorithm' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/174418/