简体   繁体   English

信息隐藏与OCaml记录

[英]Information hiding with OCaml records

Given 特定

type 'a set = { insert : 'a -> 'a set; contains : 'a -> bool }

How can I implement 我该如何实施?

val empty : 'a set

?

I've tried closing over something, say a list, but the return type is wrong.. since it is. 我试过关闭某些东西,比如列表,但返回类型是错误的..因为它是。 (ignoring the fact that the performance characteristics here are terrible :-) ) (忽略这里的性能特征非常糟糕的事实:-))

let empty =
  let rec insert_f set a =
    match set with
    | [] -> a :: []
    | k :: rest ->
        if k = a then
          k :: rest
        else
          k :: insert_f rest a
  in
    let rec contains_f set a =
      match set with
      | [] -> false
      | k :: rest ->
          if k = key then
            true
          else contains_f rest a
    in
      { insert = insert_f []; contains = contains_f []}

directly writing the empty is not the easiest in such data structure, as you will need to write the insert, which will contains again an insert and so one... So let's write first the insert: 在这样的数据结构中直接写空并不是最简单的,因为你需要编写插入,它将再次包含一个插入,所以...所以让我们先写插入:

let rec insert : 'a set -> 'a -> 'a set = fun s x -> {
  insert = (fun y -> failwith "TODO");
  contains = (fun y -> if x = y then true else s.contains y) }

in insert, you want to recursively call insert, but the first parameter will be the record you are writing. 在insert中,您希望以递归方式调用insert,但第一个参数将是您正在编写的记录。 So here is the complete solution: 所以这是完整的解决方案:

let rec insert : 'a set -> 'a -> 'a set = fun s x ->
  let rec ss = {
    insert = ( fun y -> insert ss y);
    contains = (fun y -> if x = y then true else s.contains y)}
  in ss

let rec empty = {
  insert = (fun x -> insert empty x);
  contains = (fun x -> false)}

First of all, it's bool, not boolean. 首先,它是布尔,而不是布尔。 :) :)

Second, this definition is quite cumbersome. 其次,这个定义非常麻烦。 But you can do something like: 但你可以这样做:

let empty = {
  insert=(fun x -> {
           insert=(fun x -> assert false);
           contains=(fun x-> assert false)});
  contains=(fun x -> false)}

with your implementations of insert and contains for non-empty sets in place of "assert false" of course. 用你的insert实现和包含非空集代替“断言错误”当然。

A hint for implementing insert and contains: don't use any lists, use compositions of a functions from existing and new sets. 实现insert和contains的提示:不使用任何列表,使用现有和新集合中的函数组合。

You can find nice examples in eg "On Understanding Data Abstraction, Revisited" by W. Cook, that paper is available online. 您可以在例如W. Cook的“On Understanding Data Abstraction,Revisited”中找到很好的例子,该论文可在线获取。

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

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