gpt4 book ai didi

haskell - 遍历具有任意数量分支的树

转载 作者:行者123 更新时间:2023-12-02 11:08:08 27 4
gpt4 key购买 nike

我想计算具有任意数量分支的的最大度数。

data Tree a = Node a [Tree a]
deriving (Eq, Show)

{-

2
/ | \
7 3 1
| / \
0 3 2
For this case: Answer will be 3.
-}
tree1 :: Tree Int
tree1 = Node 2 [Node 7 [], Node 3 [Node 0 []], Node 1 [Node 3 [], Node 2 []]]

--I am doing something like this:

maxBranching :: Tree Int -> Int
maxBranching Node n [] = 1
maxBranching Node n xs = max (length xs) maxBranching xs

现在,我收到一个错误。我怎样才能编写正确的模式来解决这个问题?

最佳答案

首先,maxBranching 的参数类型是 Tree Int 而不是 [Tree Int] 并且您希望将所有子节点映射到它的最大度数,所以它应该是:

map maxBranching xs

不是

maxBranching xs

其次,参数需要放在括号中,否则,函数maxBranching就变成接受3个参数。

把它们全部写成:

maxBranching :: Tree Int -> Int
maxBranching (Node _ []) = 1
maxBranching (Node _ xs) = maximum $ (length xs) : (map maxBranching xs)

关于haskell - 遍历具有任意数量分支的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341188/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com