Sina Madani
Sina Madani

Reputation: 1324

How to sum the lengths of a collection in F#?

I'm trying to print the total number of lines for all files in a given directory. However, I get an error Type mismatch. Expecting IEnumerable<string> -> 'a but given a 'b list -> 'c list. I'm not sure why this is. Here is my code:

let printLengths path =
    let files = Directory.EnumerateFiles(path)
    let fileLengths = files |> List.map (fun dir -> Seq.length(File.ReadLines(dir)))
    printfn "%i" (List.sum fileLengths)

Upvotes: 1

Views: 109

Answers (2)

Vandroiy
Vandroiy

Reputation: 6223

System.IO.Directory.EnumerateFiles returns a sequence aka IEnumerable<'T>, not a list. Use Seq.map and Seq.sum to map or sum sequences.

Or, for a shorter solution, use Seq.sumBy:

let printTotalNumberOfLines path =
    Directory.EnumerateFiles path
    |> Seq.sumBy (File.ReadAllLines >> Seq.length)
    |> printfn "%i"

Upvotes: 6

joranvar
joranvar

Reputation: 490

You are using List.map on files, but the output of Directory.EnumerateFiles is an IEnumerable. List.map works on lists only. You could try using Seq.map instead, or convert files first with Seq.toList.

Upvotes: 3

Related Questions