简体   繁体   English

OCaml中多路树的最大值

[英]Max Value of a Multiway Tree in OCaml

I'm an IT Student and kind of a newbie to OCaml 我是一名IT学生,也是OCaml的新手

Recently, studying for an exam I found this exercise. 最近,在考试中我找到了这个练习。

Given: type 'a tree = Tree of 'a * 'a tree list 给定:键入'a tree =树'a''树列表

Define a function mtree : 'a tree ->'a, that returns the greatest value of all the nodes in a multiway tree, following the usual order relation in OCaml (<=) 定义一个函数mtree:'a tree - >'a,它返回多路树中所有节点的最大值,遵循OCaml中的通常顺序关系(<=)

I've come to do something like this below, which, of course, is not working. 我下面会做这样的事情,当然,这是行不通的。

let rec mtree (Tree (r, sub)) =
        let max_node (Tree(a, l1)) (Tree(b, l2)) =
            if a >= b then (Tree(a, l1)) else (Tree(b, l2)) in
        List.fold_left max_node r sub;;

After reading an answer to this I'm posting the fixed code. 在阅读完答案之后,我发布了固定代码。

let rec mtree (Tree(r,sub)) =
    let max_node (Tree(a, l1)) (Tree(b, l2)) =
        if a >= b then a else b in
    List.fold_left (max_node) r (List.map mtree sub);;

The idea is the same, fold the list comparing the nodes making use of my local function to do so and travel through the tree by calling the function itself over the nodes lists of the consecutive levels. 这个想法是相同的,折叠列表比较使用我的本地函数的节点,并通过在连续级别的节点列表上调用函数本身来遍历树。

Is still not working, though. 但是仍然无法正常工作。 Now complains about max_node in the fold_left part. 现在抱怨fold_left部分中的max_node。

Error: This expression has type 'a tree -> 'a tree -> 'a
       but an expression was expected of type 'a tree -> 'a tree -> 'a tree

And here I'm definitely lost because I can't see why does it expects to return an 'a tree 在这里,我肯定迷失了,因为我无法理解为什么它希望返回一棵树

This code is pretty credible (IMHO). 这段代码非常可靠(恕我直言)。 The key thing missing is that it doesn't traverse subtrees of the subtrees. 缺少的关键是它不会遍历子树的子树。 Note that you define your function as recursive (which is very reasonable), but it never calls itself. 请注意,您将函数定义为递归(这是非常合理的),但它从不调用自身。

Another issue to point out is that the problem statement calls for a "value" from the tree, but your code is returning a whole tree node. 需要指出的另一个问题是问题语句从树中调用“值”,但是您的代码返回整个树节点。

Answering my own question is kind of lame but with the hints received here I could finish it I'm leaving my code here for anyone facing similar problems. 回答我自己的问题有点蹩脚但是在这里收到的提示我可以完成它我将我的代码留在这里面对任何面临类似问题的人。

let maxt (Tree(r,b)) =
    let rec aux (Tree(r,b)) =
        match b with
        [] -> [r]
        |l -> [r]@( List.fold_right (@) (List.map aux b) [])
    in List.fold_left max r (aux (Tree(r,b)));;

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

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