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