[Haskell-beginners] Conciseness question

Ertugrul Soeylemez es at ertes.de
Mon Aug 8 09:48:11 CEST 2011


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

> >     import Data.Map (Map, (!), lookup)
> >
> >     lookup ConfigAppDir myDirs
> >     myDirs ! ConfigAppDir
>
> This is the solution I like. I have to accept that here I cannot reach
> the conciseness of which might be due to Haskell being strongly typed.

Note that likely this solution is no different from the Lua solution.
You are just coding directly for what you have syntactic sugar in Lua.
After all the interpreter keeps a list (or more likely a map) of
variables and just does indexing and mapping.

Also I don't find it terribly less concise.  It's just the overwhelming
import stuff, which makes the code larger in such a small example.


> > 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.
>
> Is the latter one really unsafe? I'm not quite sure how to code
> something that the compiler accepts and crashes at runtime because
> mydirs :: Map AppDir FilePath and I would believe that the compiler
> would detect if the values after the ! is not from AppDir.

The compiler cannot detect that, because you are essentially writing a
mini-interpreter.  Just like Lua cannot predetect the absence of a
variable at parse time.  To be safe you should use lookup:

    lookup :: Ord k => k -> Map k a -> Maybe a

This isn't too bad, because Maybe is a monad, and you have convenient
combinators like 'maybe':

    maybe (putStrLn "Configuration directory not specified")
          doSomethingWithConfigDir
          myAppDirs


Greets,
Ertugrul


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





More information about the Beginners mailing list