let/where

Mark Carroll mark@chaos.x-philes.com
Wed, 19 Sep 2001 13:53:22 -0400 (EDT)


There seem to be a few situations where it's not clear to me when to use
"let" and when "where". For instance, in this little example I was playing
with to work out what syntax works,

main = putStr (show (if maybe_index == Nothing then DP_Unknown else DP_Number index) ++ "\n")
       where maybe_index = maybe_read word 
             (Just index) = maybe_index

or...

main = let maybe_index = maybe_read word 
           (Just index) = maybe_index
       in putStr (show (if maybe_index == Nothing then DP_Unknown else DP_Number index) ++ "\n")

Does anyone care? At the moment I use "where" so that at a first glance
you get an overall idea of things, then you can read further for details
if you like.

I was disappointed to find that I don't seem to be able to write things
like,

main = let maybe_index = maybe_read word 
       in putStr (show (if maybe_index == Nothing then DP_Unknown else DP_Number index) ++ "\n")
          where (Just index) = maybe_index

BTW, is the above a sane way of getting the 'index' 'out of' the "Just"?
I often seem to be using a "where (Just foo) = bar" type of idiom.

(Of course, there is that special "let" stuff for "do" notation too
which doesn't seem to use "in".)

I hope all that was somewhat coherent, anyway, or at least sheds light on
some of the confusion of newcomers to Haskell!

-- Mark