我写了下面的代码来构造一个给定顶点的树,给定顶点之间的连接列表。
type Connection = (Int,Int)
data Tree = Leaf Int | Node Int [Tree] deriving (Eq,Read,Show)
makeTree :: Int -> [Connection] -> Tree
makeTree x [] = Leaf x
makeTree indx connections = Node indx otherTrees where
otherTrees = [makeTree i cx | i <- directConnections, let cx = removeConnectionsTo indx connections]
directConnections = map (\(x,y) -> if (x == indx) then y else x) $ filter (\(x,y) -> x == indx || y == indx) connections
removeConnectionsTo :: Int -> [Connection] -> [Connection]
removeConnectionsTo indx = filter (\(x,y) -> x /= indx && y /= indx)
出于某种原因,下面的输入给了我惊人的不同结果:
makeTree 1 [(1,2),(1,3)]
给我Node 1 [Leaf 2,Leaf 3]
makeTree 1 [(1,2),(1,5),(2,3),(2,4),(5,6),(5,7)]
给我Node 1 [Node 2 [Node 3 [],Node 4 []],Node 5 [Node 6 [],Node 7 []]]
我在 OS X 10.8.2 上运行 GHCi,版本 7.4.1。
我不明白为什么我在第一个示例中获得了两次 Leaf(正确),但在第二个示例中获得了空子树列表的节点(不正确)。