简体   繁体   English

Haskell定义二叉树

[英]Haskell Defining a Binary Tree

I want to define an infinite tree in Haskell using infinitree :: Tree, but want to set a pattern up for each node, defining what each node should be. 我想使用infinitree :: Tree在Haskell中定义一个无限树,但想为每个节点设置一个模式,定义每个节点应该是什么。 The pattern is 1 more then then its parent. 模式比其父级多1。 I am struggling on how to set up a tree to begin with, and how and where to define the pattern of each node? 我正在努力如何建立一棵树,如何以及在何处定义每个节点的模式?

Thank you 谢谢

Infinite data structures can generally be defined by functions which call themselves but have no base case. 无限数据结构通常可以通过调用自身但没有基本情况的函数来定义。 Usually these functions don't need to pattern match on their arguments. 通常,这些函数不需要在其参数上进行模式匹配。 For example, a list equal to [1..] can be written as 例如,等于[1..]的列表可以写成

infiniteList :: [Int]
infiniteList = go 1 where 
  go n = n : go (n+1) 

You can use the exact same technique for a tree: 您可以对树使用完全相同的技术:

data Tree a = Node (Tree a) a (Tree a) | Nil deriving (Show)

infiniteTree :: Tree Int 
infiniteTree = go 1 where 
  go n = Node (go (2*n)) n (go (2*n+1))

This defines the infinite tree 这定义了无限树

   1 
 /   \
 2   3 
/ \ / \
4 5 6 7
...

A type for infinite binary trees with no leaves: 无叶的无限二叉树的类型:

data Tree a = Tree (Tree a) a (Tree a)

One general pattern for doing this sort of thing is called unfold . 做这种事情的一种通用模式称为unfold For this particular type: 对于此特定类型:

unfold :: (a -> (a,b,a)) -> a -> Tree b

Can you see how to define this function and use it for your purpose? 您能看到如何定义此功能并将其用于您的目的吗?

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

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