Data.List.Ordered.unionAllBy comparing infinite lists

So, I have the inputs of 2 sorted lists, which can be infinite. I have to write a prod function that returns basically the product of the Cartesian coordinates of the product in sorted order.

Example:

prod [2,4,5,10] [2,3] -> [4,6,8,10,12,15,20,30]

For end lists, it's as simple as

import Data.List
prod xs ys = sort [x*y | x<-xs, y<-ys]

But the problem is that I'm trying to use it with infinite lists. I thought that since the inputs are sorted, I can use Data.List.Ordered.unionAllBy, but I cannot figure out how to use it. The comparison option confuses me.

So, I can use the function that I wrote:

sequence2 xs ys = [[i*j| i<-xs]|j<-ys]

Example:

sequence2 [2,4,5] [3,4,5] -> [[6,12,15],[8,16,20],[10,20,25]]

I assume my solution would look something like this:

Data.List.Ordered.unionAllBy (comparison) (sequence' xs ys)

Any clues how can I change this to use endless lists?

+4
1

, unionAllBy, , , compare Ord . Ord, unionAll unionAllBy.

unionAllBy ::          (a -> a -> Ordering) -> [[a]] -> [a]
unionAll   :: Ord a =>                         [[a]] -> [a]
compare    :: Ord a =>  a -> a -> Ordering

unionAll = unionAllBy compare

, : LT, EQ GT. , compare, , Ord

compare x y  
     | x == y    =  EQ  
     | x <= y    =  LT  
     | otherwise =  GT  

x <= y           =  compare x y /= GT  
x <  y           =  compare x y == LT  
x >= y           =  compare x y /= LT  
x >  y           =  compare x y == GT

unionAll sequence2, . unionAll , .

> unionAll $ sequence2 [2,4,5] [3,4,5]
[6,8,10,12,15,16,20,25]
                 ^
                 only one twenty

sequence2

> take 12 . unionAll $ sequence2 [2,4..] [3,5..]
[6,10,12,14,18,20,22,24,26,28,30,34]

, mergeAll.

> mergeAll $ sequence2 [2,4,5] [3,4,5]
[6,8,10,12,15,16,20,20,25]
                 ^  ^
                 two twenties
+4

Source: https://habr.com/ru/post/1607668/


All Articles