I have a signature
combine
:: [[a]] -> [[a]]
function Combine
takes list built f开发者_StackOverflowrom list,(1 list may be infinity, like repeat 1), and returns list
with the longest list(s) without changing their order.
combine [] = []
combine [[]] = [[]]
combine [[], [1]] = [[1]]
combine [[1], [2]] = [[1],[2]]
combine [[], repeat 1, []] = [repeat 1] value
Any ideas? Thank you Code:
combine :: [[a]] -> [[a]] combine [] = []combine ((xs),[]) = [xs] doesnt work for some reason
You will need to solve this with a recursive function.
Consider a recursive algorithm that builds an accumulator -- ask for clarification if you are not familiar with the concept of an accumulator. This accumulator will have type [[a]]
, which is the same as our function's return type. As we iterate over the list of lists using a recursive function, we cons lists onto the accumulator if they are the same length as other lists in the accumulator, or ignore them if they are of less length. However, if the list is of greater length, we scrap everything else in the accumulator and only keep the new, longer list.
This vaguely describes a linear algorithm you may use to solve this problem. Please ask questions in the comments if you wish for more clarification.
First, you need a compare function, e.g.:
cmp [] [] = EQ
cmp [] _ = LT
cmp _ [] = GT
cmp (x:xs) (y:ys) = cmp xs ys
Then you can use a helper function that has an accumulator for the current "maximums":
combine :: [[a]] -> [[a]]
combine [] = []
combine (x:xs) = comb xs [x] where
comb [] acc = acc
comb (x:xs) (y:ys) = case x `cmp` y of
EQ -> ???
LT -> ???
GT -> ???
I think you can figure out what to do in the different cases...
精彩评论