【问题标题】:Counting number of nodes in tree in ocaml在ocaml中计算树中的节点数
【发布时间】:2016-05-20 00:19:38
【问题描述】:

我正在编写一个程序,该程序应计算 ocaml 中给定树中的节点数。

type 'a tree = Node of 'a * 'a tree list

let count tree = 
    let rec visit node =
      let (_,list_of_children) = node in
      let rec help list1 = 
        match list1 with 
        | [] -> 0
        | h::t -> (help t) + (visit h)  in
     (List.length list_of_children) + 1 + help list_of_children in
    visit tree

但是,代码不起作用。这是编译器所说的:

文件“liscie5.ml”,第 10 行,字符 44-60:错误:此表达式 有类型'一个列表 但是需要一个类型为 ('b * 'a list) 列表的表达式

(第 10 行:(List.length list_of_children) + 1 + help list_of_children 中)。

你知道我的代码有什么问题吗?

【问题讨论】:

  • 你应该学习和使用List.fold_left。我建议使用List.fold_left 重新实现List.length,然后对其进行修改以解决您的问题。

标签: tree ocaml


【解决方案1】:

我看到的第一个问题是这样的:

let (_,list_of_children) = node in

大概node'a tree 类型。因此它看起来像Node (value, children)。但是这行代码将其视为一对通用的 OCaml 值 (a, b)。改为这样写会有所帮助:

let Node (_,list_of_children) = node in

有更简洁的方法来写这个,但它应该有助于取得一点进步。毫无疑问还有其他(可能类似的)问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多