您的第一个定义kart xs ys = [(x,y) | x <- xs, y <- ys] 相当于
kart xs ys = xs >>= (\x ->
ys >>= (\y -> [(x,y)]))
在哪里
(x:xs) >>= g = g x ++ (xs >>= g)
(x:xs) ++ ys = x : (xs ++ ys)
是顺序操作。将它们重新定义为交替操作,
(x:xs) >>/ g = g x +/ (xs >>/ g)
(x:xs) +/ ys = x : (ys +/ xs)
[] +/ ys = ys
你的定义也应该适用于无限列表:
kart_i xs ys = xs >>/ (\x ->
ys >>/ (\y -> [(x,y)]))
测试,
Prelude> take 20 $ kart_i [1..] [101..]
[(1,101),(2,101),(1,102),(3,101),(1,103),(2,102),(1,104),(4,101),(1,105),(2,103)
,(1,106),(3,102),(1,107),(2,104),(1,108),(5,101),(1,109),(2,105),(1,110),(3,103)]
感谢"The Reasoned Schemer"。 (另见conda, condi, conde, condu)。
另一种更明确的方法是创建单独的子流并将它们组合起来:
kart_i2 xs ys = foldr g [] [map (x,) ys | x <- xs]
where
g a b = head a : head b : g (tail a) (tail b)
这实际上产生了完全相同的结果。但是现在我们对如何组合子流有了更多的控制权。我们可以be more diagonal:
kart_i3 xs ys = g [] [map (x,) ys | x <- xs]
where -- works both for finite
g [] [] = [] -- and infinite lists
g a b = concatMap (take 1) a
++ g (filter (not . null) (take 1 b ++ map (drop 1) a))
(drop 1 b)
所以现在我们得到
Prelude> take 20 $ kart_i3 [1..] [101..]
[(1,101),(2,101),(1,102),(3,101),(2,102),(1,103),(4,101),(3,102),(2,103),(1,104)
,(5,101),(4,102),(3,103),(2,104),(1,105),(6,101),(5,102),(4,103),(3,104),(2,105)]
有了一些searching on SO,我还发现了一个answer by Norman Ramsey,它似乎还有另一种生成序列的方法,将这些子流分成四个区域——左上角、顶行、左列,并递归地休息。他的merge 和我们这里的+/ 一样。
你的第二个定义,
genFromPair (e1, e2) = [x*e1 + y*e2 | x <- [0..], y <- [0..]]
相当于只是
genFromPair (e1, e2) = [0*e1 + y*e2 | y <- [0..]]
因为[0..] 列表是无限的,所以x 的任何其他值都没有机会发挥作用。 这是以上定义都尽量避免的问题。