Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Created January 1, 2019 14:32
Show Gist options
  • Save DonaldKellett/dbb93184a635e0a7b455a118d0ae26e4 to your computer and use it in GitHub Desktop.
Save DonaldKellett/dbb93184a635e0a7b455a118d0ae26e4 to your computer and use it in GitHub Desktop.
PureScript by Example - 4.17 Listing All Files - Exercise 1-3 Solutions
module FileOperations where
-- 4.17 Listing All Files of PureScript by Example
-- N.B. This module relies extensively on a non-standard module Data.Path
-- whose source code can be found on
-- https://github.com/paf31/purescript-book/blob/master/exercises/chapter4/src/Data/Path.purs
import Prelude
import Data.Array
import Partial.Unsafe
import Data.Maybe
import Data.Path
-- Boilerplate code provided in 4.17 Listing All Files of PureScript by Example
allFiles :: Path -> Array Path
allFiles file = file : concatMap allFiles (ls file)
allFiles' :: Path -> Array Path
allFiles' file = file : do
child <- ls file
allFiles' child
-- Exercise 1
onlyFiles :: Path -> Array Path
onlyFiles path = if isDirectory path
then concatMap onlyFiles (ls path)
else pure path
-- Exercise 2
largestFile :: Path -> Path
largestFile path =
foldl (\file1 file2 -> if unsafePartial fromJust (size file1) > unsafePartial fromJust (size file2)
then file1
else file2) (unsafePartial fromJust (head files)) files
where
files :: Array Path
files = onlyFiles path
smallestFile :: Path -> Path
smallestFile path =
foldl (\file1 file2 -> if unsafePartial fromJust (size file1) < unsafePartial fromJust (size file2)
then file1
else file2) (unsafePartial fromJust (head files)) files
where
files :: Array Path
files = onlyFiles path
-- Exercise 3
whereIs :: String -> Maybe Path
whereIs = whereIs' root
where
whereIs' :: Path -> String -> Maybe Path
whereIs' path name = if isDirectory path
then (if null otherResults then result' else head otherResults)
else Nothing
where
result' :: Maybe Path
result' = if elem name (map filename (onlyFiles path))
then Just path
else Nothing
otherResults :: Array Path
otherResults =
catMaybes (map (\path -> whereIs' path name) (ls path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment