wolf
wolf

Reputation: 419

How to count files in the FileSystem

FileSystem = [Dir ("Dir3",[]); Dir ("Dir1",[Dir ("Dir2",[])])]

Let's suppose that this is my FileSystem. I want to count the number of files in that FileSystem recursively. Can someone guide me through this? I could not find related documentation and don't know where to look.

 type FileSystem = Element list and Element = | File of string | Dir of string * FileSystem

My FileSystem structure is like above.

Upvotes: 1

Views: 131

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

This type of recursive query usually relies on a fold function to traverse the hierarchy.

A fold function takes a function that can be used to aggregate the results. In the below example, the inner counter function takes the accumulated count so far, and the next element in the list. We then check the element, and if it's a file we add 1 to our count, otherwise we add the count of files in child subdirectories.

let rec countFiles =
             let counter i el =
                 i + match el with
                     | File _ -> 1
                     | Dir (_, children) -> countFiles children
             List.fold counter 0

Running the following:

printfn "%A" <| countFiles
    [ File "a"
      Dir ("d1", [
                  File "b"
                  File "c"
                  ])
      ]

// yields 3

Upvotes: 1

Related Questions