简体   繁体   English

在Haskell中生成n元二叉树

[英]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. 我遇到的问题是,我什至不知道如何生成深度为(例如)2的树,该树仅以“ Lambda”作为节点。 If someone could help me with generating this simple tree (depth 2) I could generate them randomly. 如果有人可以帮助我生成此简单树(深度2),则可以随机生成它们。 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. 由于函数构建本身希望将Tree作为输入,因此它将无法正常工作。 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. 实际上,我需要具有Lambda或Funktion节点的树,但首先,我需要了解如何生成此结构的简单版本。

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 这样build 4 "A"将产生

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. 你靠近-你build此刻功能将始终返回Leaf ,作为递归的基本情况并没有它的参数什么。 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. 这将产生您的build功能似乎想要的功能,即给定深度n的简单“树”,由一个Leaf节点和Lambda节点组成。 Eg: 例如:

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

To get your randomly generated tree, you need to look at the System.Random module. 要获取随机生成的树,您需要查看System.Random模块。

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. 可以对其进行扩展和修改,以产生所需的行为(完全随机生成的树),但需要了解monad等,这可能需要一些额外的阅读材料。

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

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