Learning.Writer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Control.Applicative (liftA)
import Control.Monad.Writer
import Data.Bool
import System.Directory (canonicalizePath, doesDirectoryExist, renameFile)
import System.FilePath (dropTrailingPathSeparator)

path :: FilePath -> IO (Maybe FilePath)
path p =
  ifM
    (doesDirectoryExist p)
    (return Nothing)
    (liftA Just (canonicalizePath . dropTrailingPathSeparator $ p))
    --(mapM canonicalizePath (return . dropTrailingPathSeparator $ p))

path' :: FilePath -> IO (Writer [String] (Maybe FilePath))
path' p =
  liftA
    (maybe
       (writer (Nothing, ["Directory `" ++ p ++ "` does not exist."]))
       (const . writer $ (Just p, [""])))
    (path p)

ifM
  :: Monad m
  => m Bool -> m a -> m a -> m a
ifM p t f = p >>= bool f t