Combining two nested lists as one nested list

haskell

130 观看

1回复

223 作者的声誉

I want to combine two lists of lists and get a new nested list,Here is my code:

getAllPaths ::(Eq a) => [(a,a)] -> [[a]]
getAllPaths [] = [[]]
getAllPaths (x:xs) = findAllPath (fst x) xs ++ getAllPaths xs

I want to combine the nested list returned from the findAllPath with all the elements from the recursive calls which are also nested list.

I know that ++ is used for combining two lists and no nested list but i also can't use first concat and then ++ because then list will be flatten.

Here is the type signature of findAllPath and function also:

   findAllPath ::(Eq a) => a -> [(a,a)] -> [[a]]
   findAllPath val list = path val list
            where
                (first,second) = partition((==val).fst) list
                singl = map snd first
                path val list
                            | first == [] = [[val]]
                            | otherwise = map ((:) val) $ concat $ map (\x -> findAllPath x list) singl

This functionr returns all the possible paths from one node. I want to collect all the possible paths from all nodes.

For example, there are few paths from node 1 and 2 like this:

from node 1 to [[1,2,3],[1,4,6]]

from node 2 to [[2,7,9],[2,0,6]]]

and i want a combination of [[1,2,3],[1,4,6],[2,7,9],[2,0,6]]

Can someone tell me how do it combine them in recursive call?

作者: Khan Saab 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


2

37236 作者的声誉

决定

As WillemVanOnsem mentions in the comments, you're looking for (++). It may not be immediately obvious from the type signature but consider:

(++) :: [a] -> [a] -> [a]
-- if a ~ [b] then the specific type is:
(++) :: [[b]] -> [[b]] -> [[b]]

And by experiment:

GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> [[1,2,3],[1,4,6]] ++ [[2,7,9],[2,0,6]]
[[1,2,3],[1,4,6],[2,7,9],[2,0,6]]

If you have a whole list of these, you can combine with foldr.

foldr (++) [] (results :: [[[a]]])

or indeed concat

concat (results :: [[[a]]])
作者: Adam Smith 发布者: 27.12.2017 06:52
32x32