[Haskell-beginners] Expected / Inferred mis-match and confused!

Sean Charles sean at objitsu.com
Thu Jun 9 18:26:18 CEST 2011

Here are the snippets of my code currently hurting my coding ulcer...

routes :: [Record] -> IO ()
routes legodata = do
   let all = foldl forwardRoutes M.empty legodata -- [Record]
   return ()

forwardRoutes :: M.Map String [String] -> Record -> M.Map String [String]
forwardRoutes map row =
   let key = row !! 0 in
   let val = row !! 1 in
   case lookup key map of
     Nothing     -> M.insert key [val] map
     Just routes -> M.insert key val:routes map

-- some 'deductions' by me, probably erroneous, to help me try to figure 
it out
--if legodata is [Record]
--   then row is Record  => [Field]
-- if map is "String [String]"
--   then key is Field because row is [Field]
--   then val is Field because row is [Field]
--   Field is "String"
-- lookup key map => lookup String M.Map String [String]

If I am fold-ing over [Record] then I assume that the data that is 
passed to the callback function is of the type Record, i.e. a single 
thing from the list of things. Record is defined as [Field] so 
presumably I could use [Field] or Record in my function 'forwardRoutes'.

When I compile the above I get:

     Couldn't match expected type `[(Field, b)]'
            against inferred type `M.Map String [String]'
     In the second argument of `lookup', namely `map'
     In the expression: lookup key map
     In the expression:
         case lookup key map of {
           Nothing -> M.insert key [val] map
           Just routes -> M.insert key val : routes map }

I have spent a long time searching and reading and trying to fathom it 
out from first principles but I cannot for the life of me figure out 
where '[(Field, b)]' is coming from! I can smell Field in there because 
Record is typed as [Field], but a tuple? And what is 'b' ?

The 'inferred type' matches what I thought it should be in the error 
message and I am right (I think) in stating that the 'expected type' is 
what it actually got from the code at compile time?!


More information about the Beginners mailing list