我最近开始使用 Haskell,可能会持续一段时间。只是被要求使用它来更好地理解我在 Uni 上的一门课程的函数式编程。
现在我有一个小问题,我目前正在尝试做的事情。我想以广度优先构建它,但我认为我的条件搞砸了,或者我的条件也错了。
所以基本上如果我给它
[“A1-Gate”, “North-Region”, “South-Region”, “Convention Center”, “Rectorate”, “Academic Building1”, “Academic Building2”]
and [0.0, 0.5, 0.7, 0.3, 0.6, 1.2, 1.4, 1.2]
,我的树应该像
但是我的试运行结果不是我预期的哈哈。因此,Haskell 的一位特别敏锐的专家可能会帮助我发现我做错了什么。输出:
*Main> l1 = ["A1-Gate", "North-Region", "South-Region", "Convention Center",
"Rectorate", "Academic Building1", "Academic Building2"]
*Main> l3 = [0.0, 0.5, 0.7, 0.3, 0.6, 1.2, 1.4, 1.2]
*Main> parkingtree = createBinaryParkingTree l1 l3
*Main> parkingtree
Node "North-Region" 0.5
(Node "A1-Gate" 0.0 EmptyTree EmptyTree)
(Node "Convention Center" 0.3
(Node "South-Region" 0.7 EmptyTree EmptyTree)
(Node "Academic Building2" 1.4
(Node "Academic Building1" 1.2 EmptyTree EmptyTree)
(Node "Rectorate" 0.6 EmptyTree EmptyTree)))
A-1 Gate 应该是根,但它最终成为一个没有孩子的孩子,所以条件非常混乱。
如果我能得到一些指导,那会有所帮助。以下是我到目前为止所写的内容:
data Tree = EmptyTree | Node [Char] Float Tree Tree deriving (Show,Eq,Ord)
insertElement location cost EmptyTree =
Node location cost EmptyTree EmptyTree
insertElement newlocation newcost (Node location cost left right) =
if (left == EmptyTree && right == EmptyTree)
then Node location cost (insertElement newlocation newcost EmptyTree)
right
else if (left == EmptyTree && right /= EmptyTree)
then Node location cost (insertElement newlocation newcost EmptyTree)
right
else if (left /= EmptyTree && right == EmptyTree)
then Node location cost left
(insertElement newlocation newcost EmptyTree)
else Node newlocation newcost EmptyTree
(Node location cost left right)
buildBPT [] = EmptyTree
--buildBPT (xs:[]) = insertElement (fst xs) (snd xs) (buildBPT [])
buildBPT (x:xs) = insertElement (fst x) (snd x) (buildBPT xs)
createBinaryParkingTree a b = buildBPT (zip a b)
感谢您提供的任何指导。是的,我已经查看了一些类似的问题,但我确实认为我的问题有所不同,但如果您认为某个帖子有一个明确的答案,这将有助于我愿意去看看它。