[Haskell-beginners] create a directory

Daniel Fischer daniel.is.fischer at web.de
Mon Nov 29 22:01:57 CET 2010

On Monday 29 November 2010 20:16:32, José Romildo Malaquias wrote:
> Hello.
> I need a function to create a directory given its path. The function
> should return a "Maybe FilePath": "Nothing" for a failure, and "Just
> path" otherwise.

Two functions come to mind, both from System.Directory.
- doesDirectoryExist
- createDirectoryIfMissing

The IO-action without error handling would be

import Control.Monad (unless)

mkDir :: FilePath -> IO FilePath
mkDir path = do
  ex <- doesDirectoryExist path
  unless ex (createDirectoryIfMissing True path)
  return path

> As I am not yet good at exception handling, would someone help me with
> this function?

To handle exceptions,

import Control.Exception as Ex

safeMkDir :: FilePath -> IO (Maybe FilePath)
safeMkDir path = (fmap Just $ mkDir path) `Ex.catch` 
                       (\(e :: SomeException) -> return Nothing)

well, you should better think which exceptions to actually catch and which 
not, so you'd better use Control.Exception.catches and a list of handlers 
for the exceptions you want to catch or catchJust.

> Romildo

More information about the Beginners mailing list