Removing syntactic sugar: List comprehension in Haskell

后端 未结 4 1065
星月不相逢
星月不相逢 2020-12-03 14:43

Can I unsugar list comprehension in this expression:

[(i,j) | i <- [1..4], j <- [i+1..4]]

This is the output:

[(1,2),         


        
4条回答
  •  孤街浪徒
    2020-12-03 14:51

    There is yet another translation scheme, it is due to Wadler, as far as I know.

    This would give:

    let
        lc_outer (x:xs) = let lc_inner (y:ys) = (x,y) : lc_inner ys
                              lc_inner []     = lc_outer xs
                          in lc_inner [x+1.. 4]
        lc_outer [] = []
    in  lc_outer [1..4]
    

    This translation avoids needless construction of singleton lists in the innermost level that would need to get flattened with concatMap later.

提交回复
热议问题