简体   繁体   English

在Haskell树中查找节点的值

[英]Finding the value of a node in a Haskell tree

I am currently messing with some Haskell trees. 我目前正在搞乱一些Haskell树。 I am new to Haskell (coming from C) and am wondering how I can find the individual value of a Node (what I've been calling a leaf) from the tree. 我是Haskell的新手(来自C),我想知道如何从树中找到一个Node(我一直称之为叶子)的单个值。 If my tree is say: (root) power, (branchLeft) 2, (branchRight) 3 如果我的树说:( root)power,(branchLeft)2,(branchRight)3

If I want to read this as, 2 to the power of three, how should I go about this? 如果我想读这个,2到3的力量,我应该怎么做呢? I'm starting from scratch and have been messing with code now for the past 3 hours and have not got very far. 我从零开始,在过去的3个小时里一直在搞乱代码而且还没有走得太远。

Any tips/ideas? 任何提示/想法?

You can model a binary tree with a binary operator in the inner nodes using an algebraic data type: 您可以使用代数数据类型在内部节点中使用二元运算符对二叉树进行建模:

data Tree a = Leaf a | InnerNode (a -> a -> a) (Tree a) (Tree a) 

The function a -> a -> a is the binary operator. 函数a -> a -> a是二元运算符。 For example, a simple tree of integers could be defined as 例如,可以将简单的整数树定义为

tree :: Tree Integer
tree = InnerNode (+) (InnerNode (^) (Leaf 3) (Leaf 2)) (Leaf 5)

To evaluate or interpret the tree in the way you describe you can write a function 要按照描述的方式评估或解释树,可以编写函数

interpretTree :: Tree Integer -> Integer

To write that function, you will probably want to use pattern matching and recursion: 要编写该函数,您可能希望使用模式匹配和递归:

interpretTree (Leaf x) = x           -- the base case
interpretTree (InnerNode f l r) = ...  -- use recursion here 

For the second case, you can recursively compute the results for the subtrees and combine them using the function f . 对于第二种情况,您可以递归计算子树的结果,并使用函数f组合它们。

I'll define a data type along the lines you mentioned: 我将根据您提到的行定义数据类型:

data Tree2 b a = Leaf a | Node b (Tree2 b a) (Tree2 b a)
  deriving Show

so I'll be able to use 所以我将能够使用

example :: Tree2 (Integer -> Integer -> Integer) Integer 
example = Node (^) (Leaf 2) (Leaf 3)

The most general folding function ("catamorphism") you can make on this type is one which recurses down the structure replacing each constructor ( Leaf , Node ) with a function ( foldLeaf , foldNode ): 你可以在这种类型上做出的最常见的折叠函数(“catamorphism”)是一个用一个函数( foldLeaffoldNode )代替每个构造函数( LeafNode )的结构。

foldTree2 :: (a -> v) -> (b -> v -> v -> v) -> Tree2 b a -> v
foldTree2 foldLeaf foldNode = fold where 
   fold (Leaf a) = foldLeaf a
   fold (Node b left right) 
                 = foldNode b (fold left) (fold right)

so we should be able to define lots of functions using this, but in particular, the evaluation function you were seeking is 所以我们应该能够使用它来定义很多函数,但特别是你正在寻求的评估函数

inOrderApply :: Tree2 (a -> a -> a) a -> a
inOrderApply = foldTree2 id id
ghci> inOrderApply example
8
ghci> inOrderApply (Node (+) (Node (-) (Leaf 10) (Leaf 5))  (Node (*) (Leaf 3) (Leaf 2)))
11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM