[Haskell-beginners] Conciseness question
Manfred Lotz
manfred.lotz at arcor.de
Mon Aug 8 13:10:44 CEST 2011
On Mon, 8 Aug 2011 09:48:11 +0200
Ertugrul Soeylemez <es at ertes.de> wrote:
> 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.
Yes, of course. That is syntactic sugar in Lua.
> After all the interpreter keeps a list (or more likely a map) of
> variables and just does indexing and mapping.
Sure.
>
> 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.
>
Yeah, I can live with that.
> > > 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
>
Thanks much for the explanations you gave me (not only this reply). That
was some new stuff for me as a Haskell beginner.
--
Manfred
More information about the Beginners
mailing list