编程语言
首页 > 编程语言> > java – 改变OCaml中的模块行为

java – 改变OCaml中的模块行为

作者:互联网

我有一组我想要限制其输入的整数.我希望它表现如下:

# RestrictedIntSet.add 15 (RestrictedIntSet.make 0 10)
Exception: 15 out of acceptable range [0 .. 10]

我该如何实现呢?在Java中,它可能看起来像:

Set<Integer> restrictedSet = new HashSet<Integer>() {
    public boolean add(Integer i) {
        if (i < lowerBound || i > upperBound) {
            throw new IllegalArgumentException("out of bounds");
        }
        return super.add(i);
    }

或者,减少滥用继承:

public class RestrictedSet {

   private int lowerBound;
   private int upperBound;
   private Set elems = Sets.newHashSet();

   public RestrictedSet(int lowerBound, int upperBound) {
      this.lowerBound = lowerBound;
      this.upperBound = upperBound;
   }

   public boolean add(Integer i) {
      if (i < lowerBound || i > upperBound) {
         throw new IllegalArgumentException("out of bounds");
      }
      return elems.add(i);   
   }

   /* fill in other forwarded Set calls as needed */
}

在OCaml中执行此操作的等效,惯用方法是什么?

解决方法:

嗯,这取决于你使用哪个集合库?

使用标准库的Set模块,您可以执行以下操作:

module type RestrictedOrderedType = sig
  type t
  val compare : t -> t -> int
  val lower_bound : t
  val upper_bound : t
end

module RestrictedSet (Elem : RestrictedOrderedType) = struct
  include Set.Make(Elem)

  exception Not_in_range of Elem.t

  let check e =
    if Elem.compare e Elem.lower_bound < 0
     || Elem.compare e Elem.upper_bound > 0
    then raise (Not_in_range e)
    else e

  (* redefine a new 'add' in term of the one in Set.Make(Elem) *)
  let add e s = add (check e) s

  let singleton e = singleton (check e)
end


(* test *)
module MySet = RestrictedSet(struct
  type t = int
  let compare = compare
  let lower_bound = 0
  let upper_bound = 10
end)

let test1 = MySet.singleton 3

let test2 = MySet.add (-3) test1
(* Exception: Not_in_range (-3) *)

标签:java,ocaml
来源: https://codeday.me/bug/20190723/1513512.html