Skip to content

Instantly share code, notes, and snippets.

@sloosch
Created April 1, 2016 19:10
Show Gist options
  • Save sloosch/d6db0641eaa12af5d0d1c0435984ac0f to your computer and use it in GitHub Desktop.
Save sloosch/d6db0641eaa12af5d0d1c0435984ac0f to your computer and use it in GitHub Desktop.
Maybe Find Greatest and Smallest File
module Main where
import Prelude
import Data.Maybe
import Control.Monad.Eff.Console (print)
import Data.Foldable (class Foldable, foldl)
import Control.Alt ((<|>))
type FileSize = Int
data Path = Path FileSize | Missing
instance showPath :: Show (Path) where
show (Path a) = "Path " ++ show a
show Missing = "Missing"
size :: Path -> Maybe Int
size (Path a) = Just a
size Missing = Nothing
chooseFileWith :: (FileSize -> FileSize -> Boolean) -> Path -> Path -> Maybe Path
chooseFileWith cmpWith path1 path2 =
chooseBySize <$> size path1 <*> size path2
where
chooseBySize s1 s2 | s1 `cmpWith` s2 = path1 | otherwise = path2
findFileWith :: forall f. (Foldable f) => (Path -> Path -> Maybe Path) -> f Path -> Maybe Path
findFileWith choose = foldl acc Nothing
where
acc :: Maybe Path -> Path -> Maybe Path
acc Nothing p = const p <$> size p -- keep Nothing until there is a file having a size
acc mp1@(Just p1) p2 = choose p1 p2 <|> mp1 -- if p2 doesnt have a size fallback to p1
findGreatest :: forall f. (Foldable f) => f Path -> Maybe Path
findGreatest = findFileWith $ chooseFileWith (>)
findSmallest :: forall f. (Foldable f) => f Path -> Maybe Path
findSmallest = findFileWith $ chooseFileWith (<)
main = do
print $ findSmallest paths
print $ findGreatest paths
where
paths = [Missing, Path 3, Missing, Path 6, Path 2, Missing, Path 1, Missing]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment