可以改善F#中的“代码行算法”吗?
作者:互联网
我写了一个小脚本来遍历文件夹中的文件以计算代码行数.
脚本的核心是此功能,用于计算空白行,注释和代码. (请注意,目前它是为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
将“分类”为单独的实体可能在另一个上下文中很有用.
标签:f,c,algorithm 来源: https://codeday.me/bug/20191210/2104123.html