[project @ 2005-03-08 09:47:01 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsArrows.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsArrows]{Desugaring arrow commands}
5
6 \begin{code}
7 module DsArrows ( dsProcExpr ) where
8
9 #include "HsVersions.h"
10
11 import Match            ( matchSimply )
12 import DsUtils          ( mkErrorAppDs,
13                           mkCoreTupTy, mkCoreTup, selectSimpleMatchVarL,
14                           mkTupleCase, mkBigCoreTup, mkTupleType,
15                           mkTupleExpr, mkTupleSelector,
16                           dsReboundNames, lookupReboundName )
17 import DsMonad
18
19 import HsSyn
20 import TcHsSyn          ( hsPatType )
21
22 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
23 --     needs to see source types (newtypes etc), and sometimes not
24 --     So WATCH OUT; check each use of split*Ty functions.
25 -- Sigh.  This is a pain.
26
27 import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLet )
28
29 import TcType           ( Type, tcSplitAppTy, mkFunTy )
30 import Type             ( mkTyConApp, funArgTy )
31 import CoreSyn
32 import CoreFVs          ( exprFreeVars )
33 import CoreUtils        ( mkIfThenElse, bindNonRec, exprType )
34
35 import Id               ( Id, idType )
36 import Name             ( Name )
37 import PrelInfo         ( pAT_ERROR_ID )
38 import DataCon          ( dataConWrapId )
39 import TysWiredIn       ( tupleCon )
40 import BasicTypes       ( Boxity(..) )
41 import PrelNames        ( eitherTyConName, leftDataConName, rightDataConName,
42                           arrAName, composeAName, firstAName,
43                           appAName, choiceAName, loopAName )
44 import Util             ( mapAccumL )
45 import Outputable
46
47 import HsUtils          ( collectPatBinders, collectPatsBinders )
48 import VarSet           ( IdSet, mkVarSet, varSetElems,
49                           intersectVarSet, minusVarSet, extendVarSetList, 
50                           unionVarSet, unionVarSets, elemVarSet )
51 import SrcLoc           ( Located(..), unLoc, noLoc, getLoc )
52 \end{code}
53
54 \begin{code}
55 data DsCmdEnv = DsCmdEnv {
56         meth_binds :: [CoreBind],
57         arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
58     }
59
60 mkCmdEnv :: ReboundNames Id -> DsM DsCmdEnv
61 mkCmdEnv ids
62   = dsReboundNames ids                  `thenDs` \ (meth_binds, ds_meths) ->
63     return $ DsCmdEnv {
64                 meth_binds = meth_binds,
65                 arr_id     = lookupReboundName ds_meths arrAName,
66                 compose_id = lookupReboundName ds_meths composeAName,
67                 first_id   = lookupReboundName ds_meths firstAName,
68                 app_id     = lookupReboundName ds_meths appAName,
69                 choice_id  = lookupReboundName ds_meths choiceAName,
70                 loop_id    = lookupReboundName ds_meths loopAName
71             }
72
73 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
74 bindCmdEnv ids body = foldr Let body (meth_binds ids)
75
76 -- arr :: forall b c. (b -> c) -> a b c
77 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
78 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
79
80 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
81 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
82                 CoreExpr -> CoreExpr -> CoreExpr
83 do_compose ids b_ty c_ty d_ty f g
84   = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
85
86 -- first :: forall b c d. a b c -> a (b,d) (c,d)
87 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
88 do_first ids b_ty c_ty d_ty f
89   = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
90
91 -- app :: forall b c. a (a b c, b) c
92 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
93 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
94
95 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
96 -- note the swapping of d and c
97 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
98                 CoreExpr -> CoreExpr -> CoreExpr
99 do_choice ids b_ty c_ty d_ty f g
100   = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
101
102 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
103 -- note the swapping of d and c
104 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
105 do_loop ids b_ty c_ty d_ty f
106   = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
107
108 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
109 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
110                 CoreExpr -> CoreExpr -> CoreExpr
111 do_map_arrow ids b_ty c_ty d_ty f c
112   = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
113
114 mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr
115 mkFailExpr ctxt ty
116   = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
117
118 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
119 mkSndExpr :: Type -> Type -> DsM CoreExpr
120 mkSndExpr a_ty b_ty
121   = newSysLocalDs a_ty                  `thenDs` \ a_var ->
122     newSysLocalDs b_ty                  `thenDs` \ b_var ->
123     newSysLocalDs (mkCorePairTy a_ty b_ty)      `thenDs` \ pair_var ->
124     returnDs (Lam pair_var
125                   (coreCasePair pair_var a_var b_var (Var b_var)))
126 \end{code}
127
128 Build case analysis of a tuple.  This cannot be done in the DsM monad,
129 because the list of variables is typically not yet defined.
130
131 \begin{code}
132 -- coreCaseTuple [u1..] v [x1..xn] body
133 --      = case v of v { (x1, .., xn) -> body }
134 -- But the matching may be nested if the tuple is very big
135
136 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
137 coreCaseTuple uniqs scrut_var vars body
138   = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
139
140 coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
141 coreCasePair scrut_var var1 var2 body
142   = Case (Var scrut_var) scrut_var (exprType body)
143          [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
144 \end{code}
145
146 \begin{code}
147 mkCorePairTy :: Type -> Type -> Type
148 mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]
149
150 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
151 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
152 \end{code}
153
154 The input is divided into a local environment, which is a flat tuple
155 (unless it's too big), and a stack, each element of which is paired
156 with the stack in turn.  In general, the input has the form
157
158         (...((x1,...,xn),s1),...sk)
159
160 where xi are the environment values, and si the ones on the stack,
161 with s1 being the "top", the first one to be matched with a lambda.
162
163 \begin{code}
164 envStackType :: [Id] -> [Type] -> Type
165 envStackType ids stack_tys = foldl mkCorePairTy (mkTupleType ids) stack_tys
166
167 ----------------------------------------------
168 --              buildEnvStack
169 --
170 --      (...((x1,...,xn),s1),...sk)
171
172 buildEnvStack :: [Id] -> [Id] -> CoreExpr
173 buildEnvStack env_ids stack_ids
174   = foldl mkCorePairExpr (mkTupleExpr env_ids) (map Var stack_ids)
175
176 ----------------------------------------------
177 --              matchEnvStack
178 --
179 --      \ (...((x1,...,xn),s1),...sk) -> e
180 --      =>
181 --      \ zk ->
182 --      case zk of (zk-1,sk) ->
183 --      ...
184 --      case z1 of (z0,s1) ->
185 --      case z0 of (x1,...,xn) ->
186 --      e
187
188 matchEnvStack   :: [Id]         -- x1..xn
189                 -> [Id]         -- s1..sk
190                 -> CoreExpr     -- e
191                 -> DsM CoreExpr
192 matchEnvStack env_ids stack_ids body
193   = newUniqueSupply                     `thenDs` \ uniqs ->
194     newSysLocalDs (mkTupleType env_ids) `thenDs` \ tup_var ->
195     matchVarStack tup_var stack_ids 
196                   (coreCaseTuple uniqs tup_var env_ids body)
197
198
199 ----------------------------------------------
200 --              matchVarStack
201 --
202 --      \ (...(z0,s1),...sk) -> e
203 --      =>
204 --      \ zk ->
205 --      case zk of (zk-1,sk) ->
206 --      ...
207 --      case z1 of (z0,s1) ->
208 --      e
209
210 matchVarStack :: Id             -- z0
211               -> [Id]           -- s1..sk
212               -> CoreExpr       -- e
213               -> DsM CoreExpr
214 matchVarStack env_id [] body
215   = returnDs (Lam env_id body)
216 matchVarStack env_id (stack_id:stack_ids) body
217   = newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
218                                         `thenDs` \ pair_id ->
219     matchVarStack pair_id stack_ids 
220                   (coreCasePair pair_id env_id stack_id body)
221 \end{code}
222
223 \begin{code}
224 mkHsTupleExpr :: [HsExpr Id] -> HsExpr Id
225 mkHsTupleExpr [e] = e
226 mkHsTupleExpr es = ExplicitTuple (map noLoc es) Boxed
227
228 mkHsPairExpr :: HsExpr Id -> HsExpr Id -> HsExpr Id
229 mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]
230
231 mkHsEnvStackExpr :: [Id] -> [Id] -> HsExpr Id
232 mkHsEnvStackExpr env_ids stack_ids
233   = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
234 \end{code}
235
236 Translation of arrow abstraction
237
238 \begin{code}
239
240 --      A | xs |- c :: [] t'        ---> c'
241 --      --------------------------
242 --      A |- proc p -> c :: a t t'  ---> arr (\ p -> (xs)) >>> c'
243 --
244 --              where (xs) is the tuple of variables bound by p
245
246 dsProcExpr
247         :: LPat Id
248         -> LHsCmdTop Id
249         -> DsM CoreExpr
250 dsProcExpr pat (L _ (HsCmdTop cmd [] cmd_ty ids))
251   = mkCmdEnv ids                        `thenDs` \ meth_ids ->
252     let
253         locals = mkVarSet (collectPatBinders pat)
254     in
255     dsfixCmd meth_ids locals [] cmd_ty cmd
256                                 `thenDs` \ (core_cmd, free_vars, env_ids) ->
257     let
258         env_ty = mkTupleType env_ids
259     in
260     mkFailExpr ProcExpr env_ty          `thenDs` \ fail_expr ->
261     selectSimpleMatchVarL pat           `thenDs` \ var ->
262     matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
263                                         `thenDs` \ match_code ->
264     let
265         pat_ty = hsPatType pat
266         proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
267                 (Lam var match_code)
268                 core_cmd
269     in
270     returnDs (bindCmdEnv meth_ids proc_code)
271 \end{code}
272
273 Translation of command judgements of the form
274
275         A | xs |- c :: [ts] t
276
277 \begin{code}
278 dsLCmd ids local_vars env_ids stack res_ty cmd
279   = dsCmd ids local_vars env_ids stack res_ty (unLoc cmd)
280
281 dsCmd   :: DsCmdEnv             -- arrow combinators
282         -> IdSet                -- set of local vars available to this command
283         -> [Id]                 -- list of vars in the input to this command
284                                 -- This is typically fed back,
285                                 -- so don't pull on it too early
286         -> [Type]               -- type of the stack
287         -> Type                 -- return type of the command
288         -> HsCmd Id             -- command to desugar
289         -> DsM (CoreExpr,       -- desugared expression
290                 IdSet)          -- set of local vars that occur free
291
292 --      A |- f :: a (t*ts) t'
293 --      A, xs |- arg :: t
294 --      -----------------------------
295 --      A | xs |- f -< arg :: [ts] t'
296 --
297 --              ---> arr (\ ((xs)*ts) -> (arg*ts)) >>> f
298
299 dsCmd ids local_vars env_ids stack res_ty
300         (HsArrApp arrow arg arrow_ty HsFirstOrderApp _)
301   = let
302         (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
303         (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
304         env_ty = mkTupleType env_ids
305     in
306     dsLExpr arrow                       `thenDs` \ core_arrow ->
307     dsLExpr arg                         `thenDs` \ core_arg ->
308     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
309     matchEnvStack env_ids stack_ids
310         (foldl mkCorePairExpr core_arg (map Var stack_ids))
311                                         `thenDs` \ core_make_arg ->
312     returnDs (do_map_arrow ids
313                 (envStackType env_ids stack)
314                 arg_ty
315                 res_ty
316                 core_make_arg
317                 core_arrow,
318               exprFreeVars core_arg `intersectVarSet` local_vars)
319
320 --      A, xs |- f :: a (t*ts) t'
321 --      A, xs |- arg :: t
322 --      ------------------------------
323 --      A | xs |- f -<< arg :: [ts] t'
324 --
325 --              ---> arr (\ ((xs)*ts) -> (f,(arg*ts))) >>> app
326
327 dsCmd ids local_vars env_ids stack res_ty
328         (HsArrApp arrow arg arrow_ty HsHigherOrderApp _)
329   = let
330         (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
331         (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
332         env_ty = mkTupleType env_ids
333     in
334     dsLExpr arrow                       `thenDs` \ core_arrow ->
335     dsLExpr arg                         `thenDs` \ core_arg ->
336     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
337     matchEnvStack env_ids stack_ids
338         (mkCorePairExpr core_arrow
339                 (foldl mkCorePairExpr core_arg (map Var stack_ids)))
340                                         `thenDs` \ core_make_pair ->
341     returnDs (do_map_arrow ids
342                 (envStackType env_ids stack)
343                 (mkCorePairTy arrow_ty arg_ty)
344                 res_ty
345                 core_make_pair
346                 (do_app ids arg_ty res_ty),
347               (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
348                 `intersectVarSet` local_vars)
349
350 --      A | ys |- c :: [t:ts] t'
351 --      A, xs  |- e :: t
352 --      ------------------------
353 --      A | xs |- c e :: [ts] t'
354 --
355 --              ---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c
356
357 dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg)
358   = dsLExpr arg                 `thenDs` \ core_arg ->
359     let
360         arg_ty = exprType core_arg
361         stack' = arg_ty:stack
362     in
363     dsfixCmd ids local_vars stack' res_ty cmd
364                                 `thenDs` \ (core_cmd, free_vars, env_ids') ->
365     mappM newSysLocalDs stack   `thenDs` \ stack_ids ->
366     newSysLocalDs arg_ty        `thenDs` \ arg_id ->
367     -- push the argument expression onto the stack
368     let
369         core_body = bindNonRec arg_id core_arg
370                         (buildEnvStack env_ids' (arg_id:stack_ids))
371     in
372     -- match the environment and stack against the input
373     matchEnvStack env_ids stack_ids core_body
374                                 `thenDs` \ core_map ->
375     returnDs (do_map_arrow ids
376                         (envStackType env_ids stack)
377                         (envStackType env_ids' stack')
378                         res_ty
379                         core_map
380                         core_cmd,
381         (exprFreeVars core_arg `intersectVarSet` local_vars)
382                 `unionVarSet` free_vars)
383
384 --      A | ys |- c :: [ts] t'
385 --      -----------------------------------------------
386 --      A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
387 --
388 --              ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
389
390 dsCmd ids local_vars env_ids stack res_ty
391     (HsLam (MatchGroup [L _ (Match pats _ (GRHSs [L _ (GRHS [L _ (ResultStmt body)])] _ ))] _))
392   = let
393         pat_vars = mkVarSet (collectPatsBinders pats)
394         local_vars' = local_vars `unionVarSet` pat_vars
395         stack' = drop (length pats) stack
396     in
397     dsfixCmd ids local_vars' stack' res_ty body
398                                 `thenDs` \ (core_body, free_vars, env_ids') ->
399     mappM newSysLocalDs stack   `thenDs` \ stack_ids ->
400
401     -- the expression is built from the inside out, so the actions
402     -- are presented in reverse order
403
404     let
405         (actual_ids, stack_ids') = splitAt (length pats) stack_ids
406         -- build a new environment, plus what's left of the stack
407         core_expr = buildEnvStack env_ids' stack_ids'
408         in_ty = envStackType env_ids stack
409         in_ty' = envStackType env_ids' stack'
410     in
411     mkFailExpr LambdaExpr in_ty'        `thenDs` \ fail_expr ->
412     -- match the patterns against the top of the old stack
413     matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
414                                         `thenDs` \ match_code ->
415     -- match the old environment and stack against the input
416     matchEnvStack env_ids stack_ids match_code
417                                         `thenDs` \ select_code ->
418     returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
419              free_vars `minusVarSet` pat_vars)
420
421 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
422   = dsLCmd ids local_vars env_ids stack res_ty cmd
423
424 --      A, xs |- e :: Bool
425 --      A | xs1 |- c1 :: [ts] t
426 --      A | xs2 |- c2 :: [ts] t
427 --      ----------------------------------------
428 --      A | xs |- if e then c1 else c2 :: [ts] t
429 --
430 --              ---> arr (\ ((xs)*ts) ->
431 --                      if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
432 --                   c1 ||| c2
433
434 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd)
435   = dsLExpr cond                        `thenDs` \ core_cond ->
436     dsfixCmd ids local_vars stack res_ty then_cmd
437                                 `thenDs` \ (core_then, fvs_then, then_ids) ->
438     dsfixCmd ids local_vars stack res_ty else_cmd
439                                 `thenDs` \ (core_else, fvs_else, else_ids) ->
440     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
441     dsLookupTyCon eitherTyConName       `thenDs` \ either_con ->
442     dsLookupDataCon leftDataConName     `thenDs` \ left_con ->
443     dsLookupDataCon rightDataConName    `thenDs` \ right_con ->
444     let
445         left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
446         right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
447
448         in_ty = envStackType env_ids stack
449         then_ty = envStackType then_ids stack
450         else_ty = envStackType else_ids stack
451         sum_ty = mkTyConApp either_con [then_ty, else_ty]
452         fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
453     in
454     matchEnvStack env_ids stack_ids
455         (mkIfThenElse core_cond
456             (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
457             (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
458                                         `thenDs` \ core_if ->
459     returnDs(do_map_arrow ids in_ty sum_ty res_ty
460                 core_if
461                 (do_choice ids then_ty else_ty res_ty core_then core_else),
462         fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
463 \end{code}
464
465 Case commands are treated in much the same way as if commands
466 (see above) except that there are more alternatives.  For example
467
468         case e of { p1 -> c1; p2 -> c2; p3 -> c3 }
469
470 is translated to
471
472         arr (\ ((xs)*ts) -> case e of
473                 p1 -> (Left (Left (xs1)*ts))
474                 p2 -> Left ((Right (xs2)*ts))
475                 p3 -> Right ((xs3)*ts)) >>>
476         (c1 ||| c2) ||| c3
477
478 The idea is to extract the commands from the case, build a balanced tree
479 of choices, and replace the commands with expressions that build tagged
480 tuples, obtaining a case expression that can be desugared normally.
481 To build all this, we use quadruples decribing segments of the list of
482 case bodies, containing the following fields:
483 1. an IdSet containing the environment variables free in the case bodies
484 2. a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
485    into the case replacing the commands
486 3. a sum type that is the common type of these expressions, and also the
487    input type of the arrow
488 4. a CoreExpr for an arrow built by combining the translated command
489    bodies with |||.
490
491 \begin{code}
492 dsCmd ids local_vars env_ids stack res_ty (HsCase exp (MatchGroup matches match_ty))
493   = dsLExpr exp                         `thenDs` \ core_exp ->
494     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
495
496     -- Extract and desugar the leaf commands in the case, building tuple
497     -- expressions that will (after tagging) replace these leaves
498
499     let
500         leaves = concatMap leavesMatch matches
501         make_branch (leaf, bound_vars)
502           = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
503                            `thenDs` \ (core_leaf, fvs, leaf_ids) ->
504             returnDs (fvs `minusVarSet` bound_vars,
505                       [noLoc $ mkHsEnvStackExpr leaf_ids stack_ids],
506                       envStackType leaf_ids stack,
507                       core_leaf)
508     in
509     mappM make_branch leaves            `thenDs` \ branches ->
510     dsLookupTyCon eitherTyConName       `thenDs` \ either_con ->
511     dsLookupDataCon leftDataConName     `thenDs` \ left_con ->
512     dsLookupDataCon rightDataConName    `thenDs` \ right_con ->
513     let
514         left_id = nlHsVar (dataConWrapId left_con)
515         right_id = nlHsVar (dataConWrapId right_con)
516         left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ TyApp left_id [ty1, ty2]) e
517         right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ TyApp right_id [ty1, ty2]) e
518
519         -- Prefix each tuple with a distinct series of Left's and Right's,
520         -- in a balanced way, keeping track of the types.
521
522         merge_branches (fvs1, builds1, in_ty1, core_exp1)
523                        (fvs2, builds2, in_ty2, core_exp2) 
524           = (fvs1 `unionVarSet` fvs2,
525              map (left_expr in_ty1 in_ty2) builds1 ++
526                 map (right_expr in_ty1 in_ty2) builds2,
527              mkTyConApp either_con [in_ty1, in_ty2],
528              do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
529         (fvs_alts, leaves', sum_ty, core_choices)
530           = foldb merge_branches branches
531
532         -- Replace the commands in the case with these tagged tuples,
533         -- yielding a HsExpr Id we can feed to dsExpr.
534
535         (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
536         in_ty = envStackType env_ids stack
537         fvs_exp = exprFreeVars core_exp `intersectVarSet` local_vars
538
539         pat_ty    = funArgTy match_ty
540         match_ty' = mkFunTy pat_ty sum_ty
541         -- Note that we replace the HsCase result type by sum_ty,
542         -- which is the type of matches'
543     in
544     dsExpr (HsCase exp (MatchGroup matches' match_ty')) `thenDs` \ core_body ->
545     matchEnvStack env_ids stack_ids core_body
546                                         `thenDs` \ core_matches ->
547     returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
548              fvs_exp `unionVarSet` fvs_alts)
549
550 --      A | ys |- c :: [ts] t
551 --      ----------------------------------
552 --      A | xs |- let binds in c :: [ts] t
553 --
554 --              ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
555
556 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
557   = let
558         defined_vars = mkVarSet (map unLoc (collectGroupBinders binds))
559         local_vars' = local_vars `unionVarSet` defined_vars
560     in
561     dsfixCmd ids local_vars' stack res_ty body
562                                 `thenDs` \ (core_body, free_vars, env_ids') ->
563     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
564     -- build a new environment, plus the stack, using the let bindings
565     dsLet binds (buildEnvStack env_ids' stack_ids)
566                                         `thenDs` \ core_binds ->
567     -- match the old environment and stack against the input
568     matchEnvStack env_ids stack_ids core_binds
569                                         `thenDs` \ core_map ->
570     returnDs (do_map_arrow ids
571                         (envStackType env_ids stack)
572                         (envStackType env_ids' stack)
573                         res_ty
574                         core_map
575                         core_body,
576         exprFreeVars core_binds `intersectVarSet` local_vars)
577
578 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts _ _)
579   = dsCmdDo ids local_vars env_ids res_ty stmts
580
581 --      A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
582 --      A | xs |- ci :: [tsi] ti
583 --      -----------------------------------
584 --      A | xs |- (|e c1 ... cn|) :: [ts] t     ---> e [t_xs] c1 ... cn
585
586 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args)
587   = let
588         env_ty = mkTupleType env_ids
589     in
590     dsLExpr op                          `thenDs` \ core_op ->
591     mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
592                                         `thenDs` \ (core_args, fv_sets) ->
593     returnDs (mkApps (App core_op (Type env_ty)) core_args,
594               unionVarSets fv_sets)
595
596 --      A | ys |- c :: [ts] t   (ys <= xs)
597 --      ---------------------
598 --      A | xs |- c :: [ts] t   ---> arr_ts (\ (xs) -> (ys)) >>> c
599
600 dsTrimCmdArg
601         :: IdSet                -- set of local vars available to this command
602         -> [Id]                 -- list of vars in the input to this command
603         -> LHsCmdTop Id -- command argument to desugar
604         -> DsM (CoreExpr,       -- desugared expression
605                 IdSet)          -- set of local vars that occur free
606 dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack cmd_ty ids))
607   = mkCmdEnv ids                        `thenDs` \ meth_ids ->
608     dsfixCmd meth_ids local_vars stack cmd_ty cmd
609                                 `thenDs` \ (core_cmd, free_vars, env_ids') ->
610     mappM newSysLocalDs stack           `thenDs` \ stack_ids ->
611     matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
612                                         `thenDs` \ trim_code ->
613     let
614         in_ty = envStackType env_ids stack
615         in_ty' = envStackType env_ids' stack
616         arg_code = if env_ids' == env_ids then core_cmd else
617                 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
618     in
619     returnDs (bindCmdEnv meth_ids arg_code, free_vars)
620
621 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
622 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
623
624 dsfixCmd
625         :: DsCmdEnv             -- arrow combinators
626         -> IdSet                -- set of local vars available to this command
627         -> [Type]               -- type of the stack
628         -> Type                 -- return type of the command
629         -> LHsCmd Id            -- command to desugar
630         -> DsM (CoreExpr,       -- desugared expression
631                 IdSet,          -- set of local vars that occur free
632                 [Id])           -- set as a list, fed back
633 dsfixCmd ids local_vars stack cmd_ty cmd
634   = fixDs (\ ~(_,_,env_ids') ->
635         dsLCmd ids local_vars env_ids' stack cmd_ty cmd
636                                         `thenDs` \ (core_cmd, free_vars) ->
637         returnDs (core_cmd, free_vars, varSetElems free_vars))
638
639 \end{code}
640
641 Translation of command judgements of the form
642
643         A | xs |- do { ss } :: [] t
644
645 \begin{code}
646
647 dsCmdDo :: DsCmdEnv             -- arrow combinators
648         -> IdSet                -- set of local vars available to this statement
649         -> [Id]                 -- list of vars in the input to this statement
650                                 -- This is typically fed back,
651                                 -- so don't pull on it too early
652         -> Type                 -- return type of the statement
653         -> [LStmt Id]   -- statements to desugar
654         -> DsM (CoreExpr,       -- desugared expression
655                 IdSet)          -- set of local vars that occur free
656
657 --      A | xs |- c :: [] t
658 --      --------------------------
659 --      A | xs |- do { c } :: [] t
660
661 dsCmdDo ids local_vars env_ids res_ty [L _ (ResultStmt cmd)]
662   = dsLCmd ids local_vars env_ids [] res_ty cmd
663
664 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts)
665   = let
666         bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
667         local_vars' = local_vars `unionVarSet` bound_vars
668     in
669     fixDs (\ ~(_,_,env_ids') ->
670         dsCmdDo ids local_vars' env_ids' res_ty stmts
671                                         `thenDs` \ (core_stmts, fv_stmts) ->
672         returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
673                                 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
674     dsCmdLStmt ids local_vars env_ids env_ids' stmt
675                                 `thenDs` \ (core_stmt, fv_stmt) ->
676     returnDs (do_compose ids
677                 (mkTupleType env_ids)
678                 (mkTupleType env_ids')
679                 res_ty
680                 core_stmt
681                 core_stmts,
682               fv_stmt)
683
684 \end{code}
685 A statement maps one local environment to another, and is represented
686 as an arrow from one tuple type to another.  A statement sequence is
687 translated to a composition of such arrows.
688 \begin{code}
689 dsCmdLStmt ids local_vars env_ids out_ids cmd
690   = dsCmdStmt ids local_vars env_ids out_ids (unLoc cmd)
691
692 dsCmdStmt
693         :: DsCmdEnv             -- arrow combinators
694         -> IdSet                -- set of local vars available to this statement
695         -> [Id]                 -- list of vars in the input to this statement
696                                 -- This is typically fed back,
697                                 -- so don't pull on it too early
698         -> [Id]                 -- list of vars in the output of this statement
699         -> Stmt Id      -- statement to desugar
700         -> DsM (CoreExpr,       -- desugared expression
701                 IdSet)          -- set of local vars that occur free
702
703 --      A | xs1 |- c :: [] t
704 --      A | xs' |- do { ss } :: [] t'
705 --      ------------------------------
706 --      A | xs |- do { c; ss } :: [] t'
707 --
708 --              ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
709 --                      arr snd >>> ss
710
711 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd c_ty)
712   = dsfixCmd ids local_vars [] c_ty cmd
713                                 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
714     matchEnvStack env_ids []
715         (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
716                                         `thenDs` \ core_mux ->
717     let
718         in_ty = mkTupleType env_ids
719         in_ty1 = mkTupleType env_ids1
720         out_ty = mkTupleType out_ids
721         before_c_ty = mkCorePairTy in_ty1 out_ty
722         after_c_ty = mkCorePairTy c_ty out_ty
723     in
724     mkSndExpr c_ty out_ty               `thenDs` \ snd_fn ->
725     returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
726                 do_compose ids before_c_ty after_c_ty out_ty
727                         (do_first ids in_ty1 c_ty out_ty core_cmd) $
728                 do_arr ids after_c_ty out_ty snd_fn,
729               extendVarSetList fv_cmd out_ids)
730   where
731
732 --      A | xs1 |- c :: [] t
733 --      A | xs' |- do { ss } :: [] t'           xs2 = xs' - defs(p)
734 --      -----------------------------------
735 --      A | xs |- do { p <- c; ss } :: [] t'
736 --
737 --              ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
738 --                      arr (\ (p, (xs2)) -> (xs')) >>> ss
739 --
740 -- It would be simpler and more consistent to do this using second,
741 -- but that's likely to be defined in terms of first.
742
743 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd)
744   = dsfixCmd ids local_vars [] (hsPatType pat) cmd
745                                 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
746     let
747         pat_ty = hsPatType pat
748         pat_vars = mkVarSet (collectPatBinders pat)
749         env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
750         env_ty2 = mkTupleType env_ids2
751     in
752
753     -- multiplexing function
754     --          \ (xs) -> ((xs1),(xs2))
755
756     matchEnvStack env_ids []
757         (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
758                                         `thenDs` \ core_mux ->
759
760     -- projection function
761     --          \ (p, (xs2)) -> (zs)
762
763     newSysLocalDs env_ty2               `thenDs` \ env_id ->
764     newUniqueSupply                     `thenDs` \ uniqs ->
765     let
766         after_c_ty = mkCorePairTy pat_ty env_ty2
767         out_ty = mkTupleType out_ids
768         body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
769     in
770     mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
771     selectSimpleMatchVarL pat           `thenDs` \ pat_id ->
772     matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
773                                         `thenDs` \ match_code ->
774     newSysLocalDs after_c_ty            `thenDs` \ pair_id ->
775     let
776         proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
777     in
778
779     -- put it all together
780     let
781         in_ty = mkTupleType env_ids
782         in_ty1 = mkTupleType env_ids1
783         in_ty2 = mkTupleType env_ids2
784         before_c_ty = mkCorePairTy in_ty1 in_ty2
785     in
786     returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
787                 do_compose ids before_c_ty after_c_ty out_ty
788                         (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
789                 do_arr ids after_c_ty out_ty proj_expr,
790               fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
791
792 --      A | xs' |- do { ss } :: [] t
793 --      --------------------------------------
794 --      A | xs |- do { let binds; ss } :: [] t
795 --
796 --              ---> arr (\ (xs) -> let binds in (xs')) >>> ss
797
798 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
799     -- build a new environment using the let bindings
800   = dsLet binds (mkTupleExpr out_ids)   `thenDs` \ core_binds ->
801     -- match the old environment against the input
802     matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
803     returnDs (do_arr ids
804                         (mkTupleType env_ids)
805                         (mkTupleType out_ids)
806                         core_map,
807         exprFreeVars core_binds `intersectVarSet` local_vars)
808
809 --      A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
810 --      A | xs' |- do { ss' } :: [] t
811 --      ------------------------------------
812 --      A | xs |- do { rec ss; ss' } :: [] t
813 --
814 --                      xs1 = xs' /\ defs(ss)
815 --                      xs2 = xs' - defs(ss)
816 --                      ys1 = ys - defs(ss)
817 --                      ys2 = ys /\ defs(ss)
818 --
819 --              ---> arr (\(xs) -> ((ys1),(xs2))) >>>
820 --                      first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
821 --                      arr (\((xs1),(xs2)) -> (xs')) >>> ss'
822
823 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss)
824   = let
825         env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
826         env2_ids = varSetElems env2_id_set
827         env2_ty = mkTupleType env2_ids
828     in
829
830     -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
831
832     newUniqueSupply             `thenDs` \ uniqs ->
833     newSysLocalDs env2_ty       `thenDs` \ env2_id ->
834     let
835         later_ty = mkTupleType later_ids
836         post_pair_ty = mkCorePairTy later_ty env2_ty
837         post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
838     in
839     matchEnvStack later_ids [env2_id] post_loop_body
840                                 `thenDs` \ post_loop_fn ->
841
842     --- loop (...)
843
844     dsRecCmd ids local_vars stmts later_ids rec_ids rhss
845                                 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
846
847     -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
848
849     let
850         env1_ty = mkTupleType env1_ids
851         pre_pair_ty = mkCorePairTy env1_ty env2_ty
852         pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
853                                         (mkTupleExpr env2_ids)
854
855     in
856     matchEnvStack env_ids [] pre_loop_body
857                                 `thenDs` \ pre_loop_fn ->
858
859     -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
860
861     let
862         env_ty = mkTupleType env_ids
863         out_ty = mkTupleType out_ids
864         core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
865                 pre_loop_fn
866                 (do_compose ids pre_pair_ty post_pair_ty out_ty
867                         (do_first ids env1_ty later_ty env2_ty
868                                 core_loop)
869                         (do_arr ids post_pair_ty out_ty
870                                 post_loop_fn))
871     in
872     returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
873
874 --      loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
875 --            ss >>>
876 --            arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
877
878 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
879   = let
880         rec_id_set = mkVarSet rec_ids
881         out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
882         out_ty = mkTupleType out_ids
883         local_vars' = local_vars `unionVarSet` rec_id_set
884     in
885
886     -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
887
888     mappM dsLExpr rhss          `thenDs` \ core_rhss ->
889     let
890         later_tuple = mkTupleExpr later_ids
891         later_ty = mkTupleType later_ids
892         rec_tuple = mkBigCoreTup core_rhss
893         rec_ty = mkTupleType rec_ids
894         out_pair = mkCorePairExpr later_tuple rec_tuple
895         out_pair_ty = mkCorePairTy later_ty rec_ty
896     in
897         matchEnvStack out_ids [] out_pair
898                                 `thenDs` \ mk_pair_fn ->
899
900     -- ss
901
902     dsfixCmdStmts ids local_vars' out_ids stmts
903                                 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
904
905     -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
906
907     newSysLocalDs rec_ty        `thenDs` \ rec_id ->
908     let
909         env1_id_set = fv_stmts `minusVarSet` rec_id_set
910         env1_ids = varSetElems env1_id_set
911         env1_ty = mkTupleType env1_ids
912         in_pair_ty = mkCorePairTy env1_ty rec_ty
913         core_body = mkBigCoreTup (map selectVar env_ids)
914           where
915             selectVar v
916                 | v `elemVarSet` rec_id_set
917                   = mkTupleSelector rec_ids v rec_id (Var rec_id)
918                 | otherwise = Var v
919     in
920     matchEnvStack env1_ids [rec_id] core_body
921                                 `thenDs` \ squash_pair_fn ->
922
923     -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
924
925     let
926         env_ty = mkTupleType env_ids
927         core_loop = do_loop ids env1_ty later_ty rec_ty
928                 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
929                         squash_pair_fn
930                         (do_compose ids env_ty out_ty out_pair_ty
931                                 core_stmts
932                                 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
933     in
934     returnDs (core_loop, env1_id_set, env1_ids)
935
936 \end{code}
937 A sequence of statements (as in a rec) is desugared to an arrow between
938 two environments
939 \begin{code}
940
941 dsfixCmdStmts
942         :: DsCmdEnv             -- arrow combinators
943         -> IdSet                -- set of local vars available to this statement
944         -> [Id]                 -- output vars of these statements
945         -> [LStmt Id]   -- statements to desugar
946         -> DsM (CoreExpr,       -- desugared expression
947                 IdSet,          -- set of local vars that occur free
948                 [Id])           -- input vars
949
950 dsfixCmdStmts ids local_vars out_ids stmts
951   = fixDs (\ ~(_,_,env_ids) ->
952         dsCmdStmts ids local_vars env_ids out_ids stmts
953                                         `thenDs` \ (core_stmts, fv_stmts) ->
954         returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
955
956 dsCmdStmts
957         :: DsCmdEnv             -- arrow combinators
958         -> IdSet                -- set of local vars available to this statement
959         -> [Id]                 -- list of vars in the input to these statements
960         -> [Id]                 -- output vars of these statements
961         -> [LStmt Id]   -- statements to desugar
962         -> DsM (CoreExpr,       -- desugared expression
963                 IdSet)          -- set of local vars that occur free
964
965 dsCmdStmts ids local_vars env_ids out_ids [stmt]
966   = dsCmdLStmt ids local_vars env_ids out_ids stmt
967
968 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
969   = let
970         bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
971         local_vars' = local_vars `unionVarSet` bound_vars
972     in
973     dsfixCmdStmts ids local_vars' out_ids stmts
974                                 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
975     dsCmdLStmt ids local_vars env_ids env_ids' stmt
976                                 `thenDs` \ (core_stmt, fv_stmt) ->
977     returnDs (do_compose ids
978                 (mkTupleType env_ids)
979                 (mkTupleType env_ids')
980                 (mkTupleType out_ids)
981                 core_stmt
982                 core_stmts,
983               fv_stmt)
984
985 \end{code}
986
987 Match a list of expressions against a list of patterns, left-to-right.
988
989 \begin{code}
990 matchSimplys :: [CoreExpr]              -- Scrutinees
991              -> HsMatchContext Name     -- Match kind
992              -> [LPat Id]               -- Patterns they should match
993              -> CoreExpr                -- Return this if they all match
994              -> CoreExpr                -- Return this if they don't
995              -> DsM CoreExpr
996 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
997 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
998   = matchSimplys exps ctxt pats result_expr fail_expr
999                                         `thenDs` \ match_code ->
1000     matchSimply exp ctxt pat match_code fail_expr
1001 \end{code}
1002
1003 List of leaf expressions, with set of variables bound in each
1004
1005 \begin{code}
1006 leavesMatch :: LMatch Id -> [(LHsExpr Id, IdSet)]
1007 leavesMatch (L _ (Match pats _ (GRHSs grhss binds)))
1008   = let
1009         defined_vars = mkVarSet (collectPatsBinders pats)
1010                         `unionVarSet`
1011                        mkVarSet (map unLoc (collectGroupBinders binds))
1012     in
1013     [(expr, 
1014       mkVarSet (map unLoc (collectStmtsBinders stmts)) 
1015         `unionVarSet` defined_vars) 
1016     | L _ (GRHS stmts) <- grhss,
1017       let L _ (ResultStmt expr) = last stmts]
1018 \end{code}
1019
1020 Replace the leaf commands in a match
1021
1022 \begin{code}
1023 replaceLeavesMatch
1024         :: Type                 -- new result type
1025         -> [LHsExpr Id] -- replacement leaf expressions of that type
1026         -> LMatch Id    -- the matches of a case command
1027         -> ([LHsExpr Id],-- remaining leaf expressions
1028             LMatch Id)  -- updated match
1029 replaceLeavesMatch res_ty leaves (L loc (Match pat mt (GRHSs grhss binds)))
1030   = let
1031         (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
1032     in
1033     (leaves', L loc (Match pat mt (GRHSs grhss' binds)))
1034
1035 replaceLeavesGRHS
1036         :: [LHsExpr Id] -- replacement leaf expressions of that type
1037         -> LGRHS Id     -- rhss of a case command
1038         -> ([LHsExpr Id],-- remaining leaf expressions
1039             LGRHS Id)   -- updated GRHS
1040 replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts))
1041   = (leaves, L loc (GRHS (init stmts ++ [L (getLoc leaf) (ResultStmt leaf)])))
1042 \end{code}
1043
1044 Balanced fold of a non-empty list.
1045
1046 \begin{code}
1047 foldb :: (a -> a -> a) -> [a] -> a
1048 foldb _ [] = error "foldb of empty list"
1049 foldb _ [x] = x
1050 foldb f xs = foldb f (fold_pairs xs)
1051   where
1052     fold_pairs [] = []
1053     fold_pairs [x] = [x]
1054     fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs
1055 \end{code}