Created
July 1, 2018 01:59
-
-
Save lqdev/60bc0499b71f60c93b48bf24c1eafcdc to your computer and use it in GitHub Desktop.
Solution to Try This Exercise in Get Programming with F# Lesson 16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Try this | |
type Folder = { | |
Name:string | |
Size:int64 | |
NumFiles:int64 | |
AvgSize:float | |
DistinctExt:string list | |
} | |
open System.IO | |
// Helper Functions | |
let getDirectories = Directory.GetDirectories >> Array.toList //Get list of Directories in specified directory | |
let getFiles = Directory.GetFiles >> Array.toList // Get list of files in specified directory | |
//Get list of FileInfo grouped by directory name | |
let getFilesInDirectory dir = | |
getFiles dir | |
|> List.map(fun x -> new FileInfo(x)) | |
|> List.groupBy(fun x -> x.DirectoryName) | |
//Extract name and directory size from | |
let getInfo (x:(string * FileInfo list)) = | |
let name,filelist = x | |
let dirSize = filelist |> List.sumBy(fun x -> x.Length) | |
(name,dirSize) | |
//Get list of subdirectories and file sizes for specified directory | |
let files = | |
getDirectories "." | |
|> List.collect getFilesInDirectory | |
|> List.map getInfo | |
|> List.sortByDescending(fun (_,x) -> x) | |
//Improvement (Returns Folder Record Type) | |
let getFolderInfo (x:(string * FileInfo list)) = | |
let name,filelist = x | |
let dirSize = filelist |> List.sumBy(fun x -> x.Length) | |
let fileCount = int64(filelist.Length) | |
let distinctext = filelist |> List.map(fun x-> x.Extension) |> List.distinct | |
let avgSize = float(dirSize / fileCount) | |
{Name=name;Size=dirSize;NumFiles=fileCount;AvgSize=avgSize;DistinctExt=distinctext} | |
//Get subdirectory folder info | |
let getSubDirectoryInfo root = | |
getDirectories root | |
|> List.collect getFilesInDirectory | |
|> List.map getFolderInfo | |
//Sort subdirectory info in descending order | |
getSubDirectoryInfo "." |> List.sortByDescending(fun folder -> folder.Size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment