【问题标题】:Imperative OCaml data structure with pointers?带有指针的命令式 OCaml 数据结构?
【发布时间】:2018-03-07 14:54:59
【问题描述】:

这样的事情可能吗?

大家好,

在我的课堂上,我们被告知使用函数式和命令式编程在 OCaml 中实现二叉搜索树。 我们正在关注 ADT 和 Pascal 中的实现,Pascal 是一种使用指针的过程语言。

这是数据结构的样子:

# Pascal
type
   tKey      = integer;
   tPos      = ^tNode;
   tNode     = record
          key         : tKey;
          left, right : tPos;
           end;      
   tBST = tPosT;

我们还获得了一些基本的 BST 操作。下面是一个例子,如果有帮助的话:

# Pascal
procedure add_key(VAR T : tBST; k:tKey);
var new, parent, child :  tBST;
begin
   createNode(new);
   new^.key := k;
   new^.left := nil;
   new^.right := nil;

   if T=nil then
      T := new
   else begin
      parent := nil;
      child := T;
      while (child <> nil) and (child^.key <> k) do begin
     parent := child;
     if k < child^.key then
        child := child^.left
     else
        child := child^.right;
      end;

      if (child = nil) then 
     if k < parent^.key then
        parent^.left := new
     else
        parent^.right := new;
        { duplicates are ignored }
   end;
end;

这就是我的功能(如果有意义的话)数据结构的样子:

type key =
    Key of int;;

type bst = 
    Empty   
    | Node of (key * bst * bst);;

但是,我在使用 OCaml 的命令方面遇到了很大的麻烦。我必须让它看起来尽可能与 Pascal 实现相似,而且我不知道 OCaml 中数据结构和指针的可能性,因为我一直使用递归等进行编程。我正在考虑使用多个“let”、if 和 else,但我不知道如何定义我的数据结构。 非常感谢您对此的大量投入。

【问题讨论】:

    标签: pointers ocaml abstract-data-type imperative


    【解决方案1】:

    据我了解,您会有这样的类型:

    type key = int
    
    type t = Empty | Node of t * key * t
    

    但是你的 add 函数不应该是这样的:

    let rec add x t =
      match t with
        | Empty ->
          Node (Empty, x, Empty)
        | Node (l, v, r) ->
          let c = compare x v in
          if c = 0 then t
          else if c < 0 then Node (add x l, v, r)
          else Node (l, v, add x r)
    

    因为这只是功能性的。

    也许您可以将类型更改为:

    type t = Empty | Node of t ref * key * t ref
    

    并尝试使add函数适应这种类型。

    【讨论】:

    • 请问elt是什么?是用来抽象节点的值吗?是的,基本上你所说的就是发生了什么。我的类型必须尽可能地看起来像帕斯卡。不仅是它的工作方式。我会试试你的类型,同时继续调查。
    • 复制/粘贴错误 ;-) 我更新了我的答案,因为它应该是 key
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多