Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you improve this 'lines of code algorithm' in F#?

Tags:

c#

algorithm

f#

I've written a little script to iterate across files in folders to count lines of code.

The heart of the script is this function to count lines of whitespace, comments, and code. (Note that for the moment it is tailored to C# and doesn't know about multi-line comments).

It just doesn't look very nice to me - has anyone got a cleaner version?

// 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
like image 955
Benjol Avatar asked Dec 03 '25 20:12

Benjol


2 Answers

I think what you have is fine, but here's some variety to mix it up. (This solution repeats your problem of ignoring trailing whitespace.)

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

"Classify" as a separate entity might be useful in another context.

like image 192
Brian Avatar answered Dec 06 '25 10:12

Brian


A better site for this might be refactormycode - it's tailored exactly for these questions.

like image 43
Tom Ritter Avatar answered Dec 06 '25 09:12

Tom Ritter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!