I was stuck trying to figure out a method of getting the latest n folders in a particular root directory using F#. The code below is the outcome of that journey and I wanted to post here and share the code sample to help other engineers trying to solve a similar problem.
open System
open System.IO
// only get the N latest FOLDERS in a directory
let getLatestNFolders (rootDirectory:string) (howmany:int) =
let latestFolders =
Directory.GetDirectories(rootDirectory)
|> Seq.cache
|> Seq.map(fun filePath -> (filePath, Directory.GetCreationTime(filePath)))
|> Seq.sortBy(fun (path, time) -> -time.Ticks) // descending order
|> Seq.take(howmany)
|> Seq.map(fun (path, time) -> path)
|> Set.ofSeq
latestFolders
let results = getLatestNFolders "c:\\temp" 3
results |> Seq.iter(fun path -> printfn "%s\n" path)
Here are some improvements, mostly focused on removing some cruft:
// only get the N latest FOLDERS in a directory
let getLatestNFolders (rootDirectory:string) howmany =
Directory.GetDirectories(rootDirectory)
|> Seq.sortBy(fun path -> -Directory.GetCreationTime(path).Ticks) // descending order
|> Seq.take howmany
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.