Lana
Lana

Reputation: 1304

Combining the results of double for loops in Haskell

I am trying to write a function which generates a list of lists and then applies a function to each of those lists and combines the results into one big list. However I am getting an error and would appreciate if someone can point me to the right direction.

The code currently looks like this:

solve_all :: [Constraint] -> Sol -> Sol -> CType -> [(Maybe Typing)]
solve_all c lam_env app_env t2= do 
  lst <- (simMatch c)
  forM lst $ \d -> do
    return $ case pleaseUnify d of  --ERROR HERE
      Right u -> Just substituteTyping u (lam_env .+. app_env, t2)
      Left _ -> Nothing

where:

simMatch :: [Constraint] -> [[Constraint]]

pleaseUnify :: [Constraint] -> Either String Unifcation

substituteTyping :: Unifcation -> Typing -> Typing

the error is pointing to the call pleaseUnify d saying I passed just one constraint instead of a list

   • Couldn't match expected type ‘[Constraint]’
                  with actual type ‘Constraint’

But I followed the answer which used forM in this question iterating through a list in haskell

and I am generating a list of lists from (simMatch c). So how come when I iterate I get only one constraint?

Upvotes: 0

Views: 102

Answers (1)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

Well let's step through it and add comments about the types

solve_all :: [Constraint] -> Sol -> Sol -> CType -> [(Maybe Typing)]
solve_all c lam_env app_env t2 = do

At this point we're in the list monad (the return value is [(Maybe Typing)]).

lst <- (simMatch c :: [[Constraint]])

We bound a variable lst to simMatch in a list monad, so lst :: [Constraint].

forM lst $ \d -> do

For each element of lst named d... so d :: Constraint.

return $ case pleaseUnify d of  --ERROR HERE

And we know pleaseUnify :: [Constraint] -> who_cares so we want d :: [Constraint] but have just above seen it must be a type Constraint.

Did you really mean to use the list monad and to name an intermediate value lst? Perhaps you intend:

forM (simMatch c) $ \d ->
 return $ case pleaseUnify d of
  Right u -> Just (substituteTyping u (lam_env .+. app_env, t2)) -- Notice a fix here too
  Left _ -> Nothing

Upvotes: 4

Related Questions