[Haskell-beginners] Conciseness question

Ertugrul Soeylemez es at ertes.de
Sun Aug 7 18:55:37 CEST 2011


Manfred Lotz <manfred.lotz at arcor.de> wrote:

> I have some 15 directories as Strings, where I want to do certain
> actions like to create those directories, or doing some other things
> to all of those directories.
>
> For doing this something like this would be good (for the sake of
> simplicity I do not write down all 15 entries)
>
> dirLst = [ "somedir", "otherdir" ]
>
> main = do
>   map makeDir dirLst
>   ...

This is possible in Haskell using the mapM_ function, but it doesn't
really solve your problem.  What you need is a foldable data structure,
which gives its entries names.  As suggested earlier, Data.Map gives you
such a structure.  You can define a custom index type like this:

    data AppDir
        = ConfigAppDir
        | DataAppDir
        | OtherAppDir
        deriving Ord

Then you can create a map from AppDir to a string:

    import Data.Map (Map)

    type AppDirs = Map AppDir FilePath

This is a foldable data structure.  Instead of mapM_ from the Prelude
you can now use mapM_ or forM_ from Data.Foldable.  To access individual
directories you can either use safe lookups or unsafe lookups:

    import Data.Map (Map, (!), lookup)

    lookup ConfigAppDir myDirs
    myDirs ! ConfigAppDir

The former is the safe variant giving you a Maybe String, while the
latter is the unsafe variant, which throws an exception, if the
directory in question is not present.

Another possibility, though more verbose, but cleaner, is to define your
own data structure and define a Foldable instance for it:

    data AppDirs a =
        AppDirs {
          configAppDir :: a,
          dataAppDir   :: a,
          otherAppDir  :: a
        }

    instance Foldable AppDirs where
        foldr f dirs =
            mconcat . map f . map ($ dirs) $
            [configAppDir, dataAppDir, otherAppDir]

I think, the Map solution is cleaner.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/





More information about the Beginners mailing list