简体   繁体   中英

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. The pattern is 1 more then then its parent. 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

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 . 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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