【问题标题】:Finding the number of the neighbours of a given node of a multiway tree (rose tree) in Haskell在 Haskell 中查找多路树(玫瑰树)的给定节点的邻居数
【发布时间】:2021-05-18 20:19:37
【问题描述】:

考虑以下对玫瑰树的定义: 树可以包含唯一的节点。

data NTree a = Nil | Node { root :: a, subtree :: [NTree a]} deriving Show
-- or just data NTree a = Nil | Node a [NTree a]

t1 :: NTree Int
t1 = Node 1 [Node 2 [ Node 5 [Nil], Node 6 [Nil], Node 7 [Nil]], Node 3 [Node 8 [Nil], Node 9 [Nil]], Node 4 [Nil]]
{-
t1:        1
        /  |  \
       /   |   \
     2     3     4
   / | \   | \
  5  6  7  8  9
-}

如何找到玫瑰树给定节点的邻居数? 举例我的意思:

--Function that finds the number of the neighbours of a given node
neighboursOf :: (Eq a) => NTree a -> a -> Int
--Examples:
print (neighboursOf t1 3) -- -> 3 (The neighbours are 1,8 and 9)
print (neighboursOf t1 1) -- -> 3 (The neighbours are 2,3 and 4)
print (neighboursOf t1 8) -- -> 1 (The neighbour is 3)
print (neighboursOf t1 10) -- -> error "Not existing node"

这个功能我不知道怎么实现

neighboursOf :: (Eq a) => NTree a -> a -> Int

你能帮我实现这个功能吗?

编辑: 我想出了这个解决方案:

data NTree a = Nil | Node {root :: a, subtree :: [NTree a] } deriving (Show , Eq)

neighborsOf :: (Eq a) => NTree a -> a -> Int
neighborsOf Nil _ = error "Empty tree"
neighborsOf tree element
    | helper tree element True == 0 = error "No such element"
    | otherwise = helper tree element True

helper ::(Eq a) => NTree a -> a -> Bool -> Int
helper Nil _ _ = 0
helper tree el isSuperior
    | root tree == el && isSuperior && subtree tree == [Nil] = 0
    | root tree == el && isSuperior = length $ subtree tree
    | root tree == el && subtree tree == [Nil] = 1
    | root tree == el = length (subtree tree) + 1
    | otherwise = helper' (subtree tree) el
        where 
            helper' :: (Eq a) => [NTree a] -> a -> Int
            helper' [] _ = 0
            helper' (tree:subtrees) el = helper tree el False  + helper' subtrees el

而且我认为这是一个非常糟糕的解决方案。您能给我一些改进的建议吗?

【问题讨论】:

  • 这是自相矛盾的。您现在说 9 是 8 的邻居。为什么 4 不是 3 的邻居?为保持一致,要么 8 应该只有一个邻居,要么 3,或者其他东西应该随着你的例子而改变。
  • @WillNess 是的,你是对的!对不起我的可怜的例子。 8 应该只有一个邻居,即 3。
  • 欢迎来到 Stack Overflow!请编辑您的问题以包含您迄今为止尝试编写的任何代码。如果您在开始时遇到困难,请考虑如何以非常小的步骤手动找到答案,并尝试为每个步骤编写一个函数并检查它是否有效。例如。 1. 在树中找到节点——树是Nil?是Node n ts吗? n 是否等于所需的标签?如果没有,你如何递归搜索ts? 2. 如果你找到了这个节点,它有多少个孩子?它是否等于subtrees 字段的长度? 3. 它有几个父母?是否总是一个?
  • 最好用更新后的问题发新帖。这样,它将获得新的观点并希望得到回应。留在这里几乎可以保证不会被注意到。 (我纯属偶然注意到您的编辑)。干杯。

标签: haskell algebraic-data-types neighbours multiway-tree


【解决方案1】:

好的,现在我们可以开始考虑了。所以你的邻居要么是节点的子节点,要么是节点的父节点。

您可以编写两个单独的函数,一个是childrenOf :: Node -> [Node],另一个是parentOf :: Node -> [Node],然后使用这两个函数的结果并将它们组合成您需要的函数。简单的。 :)

树中的节点只能有一个父节点,那么为什么我指定列表[Node] 作为parentOf 的结果?总是只有一个父母吗?

【讨论】:

  • 是的,但我不确定如何到达递归玫瑰树中的节点以识别其子节点。
  • 在给定节点的情况下,您能识别出该节点的子节点吗?
  • 不,我不能。这是我问题的主要问题。
  • 嗯,这是非常基本的 Haskell。一些教程阅读肯定会有所帮助。在这里,你可以试试GHCi> :t subtree。你能明白这是什么意思吗?
猜你喜欢
  • 2022-01-21
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 2018-08-29
相关资源
最近更新 更多