英文:
Haskell Tree Structure Explanation
问题
我目前正在尝试使用Haskell编写一个迷你极小化算法,用于连接四游戏的树。在AI的回合时,它会选择最大值的树,而在玩家回合时选择最小值的树。我已经尝试查找如何在一般情况下使用树结构,包括创建、编写、读取和遍历,但因为我是以特定方式声明树结构,所以互联网上没有返回有用的结果。
我正在实现的树结构定义如下:
data Tree a = Node a [Tree a]
我了解如何创建一个树变量,比如:
t :: Tree Int
t = Node 0 [Node 1 [], Node 2 []]
但我不知道如何实际使用它,操作它或访问节点的值。请提供任何或所有的示例和解释。
谢谢。
英文:
Im currently trying to write a minimax algorithm using tree in haskell for a connect four game where it takes maximum tree when its ai's turn and minimum when players. I've tried to find how use the tree structure in general such as : create, write, read and traverse however the internet returned with no helpful result as I'm declaring the tree in a specific way
The Tree structure that I'm implementing is defined as follows
data Tree a = Node a [Tree a ]
I understand how I can create a tree variable like
t :: Tree Int
t = Node 0 [Node 1 [], Node 2 []]
But i do not know how to actually use it or manipulate or access the node's value
please prodvide any or all examples and explanations
Thanks
答案1
得分: 2
要访问树值,你使用模式匹配,通常与递归和/或其他库函数一起使用。
例如,让我们对Tree Int
中的所有值进行求和。
sumTree :: Tree Int -> Int
sumTree (Node x ts) = x + sum (map sumTree ts)
在这里,树值被解剖为根值 x
和子树列表 ts
。然后,map sumTree ts
递归计算所有子树和的列表。我们将整数列表求和为一个单一的整数,然后添加 x
来完成。
在这个例子中,我们不必提供基本情况,因为当子树列表为空时,map
不会执行任何递归调用。
英文:
To access a tree value you use pattern matching, often together with recursion and/or other library functions.
For instance, let's sum all the values in a Tree Int
.
sumTree :: Tree Int -> Int
sumTree (Node x ts) = x + sum (map sumTree ts)
Here the tree value is dissected into the root value x
and the list of subtrees ts
. Then map sumTree ts
recurses computing the list of all the sums of the subtrees. We sum
that list of integers into a single one, and then we add x
to conclude.
In this example we did not have to provide a base case, since when the list of subtrees is empty map
does not perform any recursive call.
If you are new to Haskell, I recommend you study pattern matching in a tutorial like LYAH. It is one of the most important techniques to know in Haskell.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论