I want to build a small console program, that for given directory, will print (for now) all files inside that tree.
Here is an F# script that I came up with:
open System.IO
let getDirObjects (dir :DirectoryInfo) =
let dirs = dir.GetDirectories()
let files = dir.GetFiles()
dirs,files
let rec traverse allFiles dir =
let dirs,files = getDirObjects dir
let allFiles' = Seq.append allFiles files
let allFiles'' = dirs |> Seq.map (traverse allFiles') |> Seq.concat
Seq.append allFiles' allFiles''
let printFileInfo (fileInfo:FileInfo) =
printfn "%A" fileInfo.FullName
let printAllFilesFromDir path =
let dirInfo = DirectoryInfo path
let allFiles = traverse Seq.empty dirInfo
allFiles |> Seq.iter printFileInfo
Changelog:
#1 changed List to Seq to be more generic, no need to convert Arrays returned by GetDirectories and GetFiles to List
I've been reading about F# for past 2 weeks or so. This is actually first toy program that I wrote :)
One thing I don't like is getDirObjects
function, that returns a tuple DirectoryInfo * FileInfo
. Maybe this could be done in a more fancy way, with pattern matching or sth?
Update
Here is much shorter version, whith same output. It's get the job done, but my first intention was to do it in an F#, functional way. Please comment on the code above.
open System.IO
let printAllFilesFromDir path =
Directory.EnumerateFiles(path,"*",SearchOption.AllDirectories)
|> Seq.iter (printfn "%A")
printAllFilesFromDir "D:\_FTP"
Directory.EnumerateDirectories(path,"*",SearchOption.AllDirectories)
? \$\endgroup\$List
instead ofArray
? \$\endgroup\$Directory.EnumerateFiles
\$\endgroup\$Collections.Generic
? \$\endgroup\$Directory.EnumerateFiles
returns the fullname, if I remember correctly \$\endgroup\$