2014-12-22 2 views
4

저는 자바 배경에서 왔으며 하스켈을 배우고 싶습니다. 비트 순간에 붙어있다.트리에서 노드를 삭제하고 결과 포리스트를 반환합니다.

내가 원하는 것은 : 각 노드가 목록의 모든 트리에서 고유 한 식별자를 가진 트리 목록이 있습니다. 이제이 트리 중 하나에서 하나의 노드를 삭제하고 변경되지 않은 트리뿐만 아니라 새 트리를 반환하려고합니다.

노드를 삭제해야한다 :

  • 메이크업의 모든 어린이 말했다 새로운 나무 삭제 된 노드의
  • 삭제 부모 노드까지 루트 노드를 포함하여 모든 삭제에 대한 위를 할 수의 노드가 루트 뿐만 아니라 노드

다음 나무 상상 :

enter image description here

내가 노드를 삭제

는 '2'나는 결과는 다음과 나무가되고 싶어요 : 나무에

enter image description here

각 노드는 식별자와 자식 나무의 목록으로 구성됩니다. 여기 는 지금까지, 그러나 그것은 분명히 작동하지 않는 것을 내가 내가 하스켈과 함께이 문제를 해결하는 방법에 손실 조금 있어요 :

import Data.Tree 
data CustomNode = CustomNode { identifier :: Int } deriving (Ord,Eq,Show,Read) 
type CustomTree = Tree CustomNode 

myTree0 = t0 
    where 
     leaf i = Node CustomNode{identifier = i} [] 
     t0 = Node CustomNode{identifier = 0} [t1] 
     t1 = Node CustomNode{identifier = 1} [t2, t5] 
     t2 = Node CustomNode{identifier = 2} [leaf 3, leaf 4] 
     t5 = Node CustomNode{identifier = 5} [leaf 6] 

myTree1 = t0 
    where 
     leaf i = Node CustomNode{identifier = i} [] 
     t0 = Node CustomNode{identifier = 7} [leaf 8] 

deleteNode :: Int -> [CustomTree] -> [CustomTree] 
deleteNode _ [] = [] 
deleteNode n (x:xs) = if isNodeInTree n x then deleteNodeFromTree n x ++ xs else deleteNode n xs 
--below is the fixed line as per the answer below 
--deleteNode n (x:xs) = if isNodeInTree n x then deleteNodeFromTree n x ++ xs else x : deleteNode n xs 

deleteNodeFromTree :: Int -> CustomTree -> [CustomTree] 
deleteNodeFromTree n (Node c xs) = if identifier c == n then [] else deleteNode n xs 
--below is the fixed line as per the answer below 
--deleteNodeFromTree n (Node c xs) = if identifier c == n then xs else deleteNode n xs 

isNodeInTree :: Int -> CustomTree -> Bool 
isNodeInTree n (Node c xs) = if identifier c == n then True else isNodeInForest n xs 

isNodeInForest :: Int -> [CustomTree] -> Bool 
isNodeInForest n [] = False 
isNodeInForest n (x:xs) = if isNodeInTree n x then True else isNodeInForest n xs 

이 어떤 도움이 많이 주시면 감사하겠습니다을!

+0

@ MathematicalOrchid 예. 죄송합니다. 가져 오기를 추가하는 것을 잊었습니다. – Marco

+0

문제 없습니다. :-) – MathematicalOrchid

답변

5

여기에서 합리적인 출발을 한 것 같습니다.

나는 deleteNode 포리스트를 가져 와서 같은 포리스트를 반환하지만 지정된 노드가 제거 된 것으로 가정합니다. 이 경우

if isNodeInTree n x then ... else deleteNode n xs 

방금 ​​x 번을 던졌습니다. 당신은 아마 그것을 의미하는 것이 아닙니다.

... else x : deleteNode n xs 

은 포리스트의 해당 트리를 유지합니다. 이는 의도 한 것일 수 있습니다. deleteNodeFromTree에서 또한

는 :
if identifier c == n then [] ... 

은 아마 당신은이 시점에서 노드의 모든 자식을 반환하고 싶어? (그래서 그들은 모두 루트 노드가됩니다.)

이것들은 나에게 눈에 띄는 유일한 것입니다. 그게 너를 데려가는 곳을 보아라.

+2

놀랄만한, 그 2 개의 물건은 놓치고 있었던 모든 것이었다! 나는 그것이 더 많은 일이 될 것이라고 생각했다! 대단히 고마워, 하스켈은 실제로 꽤 굉장하다 :) – Marco

+1

@ Marco Happy Hasklling. ;-) – MathematicalOrchid

관련 문제