gpt4 book ai didi

haskell - 在 haskell 中将树缩减为列表

转载 作者:行者123 更新时间:2023-12-02 10:26:36 25 4
gpt4 key购买 nike

我正在尝试将树减少到列表,但我被困在这里..任何建议表示赞赏..

data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show)
treeToList :: (Ord a) => Tree a -> [a]
treeToList (Node root left right) = treeToList left ++ [root] ++ treeToList right

预期结果:

ghci> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5)))

[1,2,3,4,5]

最佳答案

您有两个错误:

  1. 非详尽模式(针对 Leaf 构造函数)。
  2. Node 模式中,您将 root 匹配为左树值 (Tree a),而不是 a

因此结果应如下所示:

data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show)

treeToList :: (Ord a) => Tree a -> [a]
treeToList (Leaf v) = [v]
treeToList (Node left root right) = treeToList left ++ [root] ++ treeToList right
*Main> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5)))
[1,2,3,4,5]

关于haskell - 在 haskell 中将树缩减为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815735/

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