@@ -126,20 +126,32 @@ mkForAll args ty = foldl (\t arg -> ForAll arg t Nothing) ty args
126126-- Replace a type variable, taking into account variable shadowing
127127--
128128replaceTypeVars :: String -> Type -> Type -> Type
129−replaceTypeVars = replaceTypeVars' []
129+replaceTypeVars v r = replaceAllTypeVars [(v, r)]
130+
131+-- |
132+-- Replace named type variables with types
133+--
134+replaceAllTypeVars :: [(String, Type)] -> Type -> Type
135+replaceAllTypeVars = replaceAllTypeVars' []
130136 where
131− replaceTypeVars' bound name replacement = go bound
137+ replaceAllTypeVars' bound m = go bound
132138 where
133139 go :: [String] -> Type -> Type
134− go _ (TypeVar v) | v == name = replacement
140+ go _ (TypeVar v) =
141+ case v `lookup` m of
142+ Just r -> r
143+ Nothing -> TypeVar v
135144 go bs (TypeApp t1 t2) = TypeApp (go bs t1) (go bs t2)
136145 go bs (SaturatedTypeSynonym name' ts) = SaturatedTypeSynonym name' $ map (go bs) ts
137− go bs f@(ForAll v t sco) | v == name = f
138− | v `elem` usedTypeVariables replacement =
139− let v' = genName v (name : bs ++ usedTypeVariables replacement)
140− t' = replaceTypeVars' bs v (TypeVar v') t
146+ go bs f@(ForAll v t sco) | v `elem` keys = f
147+ | v `elem` usedVars =
148+ let v' = genName v (keys ++ bs ++ usedVars)
149+ t' = replaceAllTypeVars' bs [(v, TypeVar v')] t
141150 in ForAll v' (go (v' : bs) t') sco
142151 | otherwise = ForAll v (go (v : bs) t) sco
152+ where
153+ keys = map fst m
154+ usedVars = concatMap (usedTypeVariables . snd) m
143155 go bs (ConstrainedType cs t) = ConstrainedType (map (second $ map (go bs)) cs) (go bs t)
144156 go bs (RCons name' t r) = RCons name' (go bs t) (go bs r)
145157 go _ ty = ty
@@ -149,12 +161,6 @@ replaceTypeVars = replaceTypeVars' []
149161 try n | (orig ++ show n) `elem` inUse = try (n + 1)
150162 | otherwise = orig ++ show n
151163
152−-- |
153−-- Replace named type variables with types
154−--
155−replaceAllTypeVars :: [(String, Type)] -> Type -> Type
156−replaceAllTypeVars = foldl (\f (name, ty) -> replaceTypeVars name ty . f) id
157−
158164-- |
159165-- Collect all type variables appearing in a type
160166--