[Haskell-beginners] create a directory
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:
> 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.
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)
> 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.
More information about the Beginners