我写了一个小脚本来遍历文件夹中的文件以计算代码行数。
脚本的核心是此功能,用于对空格,注释和代码行进行计数。(请注意,目前它是为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
将“分类”为单独的实体可能在另一个上下文中很有用。