我有一組輸入,我想限制它的輸入。我希望它的行爲如下:在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中做到這一點?