简体   繁体   中英

Generate n-ary binary tree in haskell

I try to create random trees from this structure:

data Tree a = Leaf a
            | Funktion (Tree a) (Tree a)
            | Lambda (Tree a)
            deriving (Show)

The problem I have is that I don't even know how to generate a tree with the depth of (for example) 2 which only has "Lambda" as nodes. If someone could help me with generating this simple tree (depth 2) I could generate them randomly. If I implement a function like this:

build (Tree a) 0 = Leaf "A"
build (Tree a) n = build (Lambda a) (n-1)

It won't work since the function build itself expects a Tree as input. Actually I need trees which have the nodes Lambda or Funktion, but first of all I need to understand how to generate a simple version of this structure.

It sounds like you want something like

build :: Natural       -- ^ Number, n, of Lambda nodes
      -> a             -- ^ Value, v, to store in the Leaf
      -> Tree a        -- ^ Lambda^n (Leaf v)
build 0 a = Leaf a
build n a = Lambda (build (n - 1) a)

So that build 4 "A" will produce

Lambda (Lambda (Lambda (Lambda (Leaf "A"))))

Unfortunately, the rest of your question (about generating random trees) really requires substantially more context to answer.

You're close - your build function at the moment will always return a Leaf , as the base case of the recursion doesn't do anything with its argument. You don't actually need the argument:

build :: Integer -> Tree String
build 0 = Leaf "A"
build n = Lambda $ build (n-1)

This would produce what your build function seems to be intending, that is a simple "tree" of given depth n composed of a Leaf node and Lambda nodes. Eg:

λ> build 2
Lambda (Lambda (Leaf "A"))

To get your randomly generated tree, you need to look at the System.Random module.

For example building on the previous, a tree of random height between a given upper and lower bound:

buildRandom :: (Integer, Integer) -> IO (Tree String)
buildRandom bounds = randomRIO bounds >>= return . build

This can be extended and modified to produce the behaviour you want (a fully random generated tree), but requires knowledge of monads etc., which might take some extra reading.

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