c# - 你能在 F# 中改进这个 'lines of code algorithm' 吗?

标签 c# algorithm 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

将“分类”作为一个单独的实体在其他情况下可能会有用。

关于c# - 你能在 F# 中改进这个 'lines of code algorithm' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/174418/

相关文章:

C++ 返回泛型类型集合的正确方法

algorithm - 您将如何生成默认的用户个人资料图片?

f# - 计算表达式中的运行方法

c# - 空引用异常 - 为什么?

c# - 具有存储库模式的 Entity Framework 插入多对多

c# - 如何在组合框的顶部插入项目?

java - 将子对象分配给基础是可能的,但如果对集合执行相同的操作,则不可能

python - 带有 bins 值百分比的直方图?

f# - 打破迭代并获得值和状态?

f# - 为什么这个 F# 函数需要括号?