Racket - 函数参数的契约是否可以依赖于另一个参数的值?

时间:2016-03-29 01:06:23

标签: racket contract

我们说我有一个功能:

(define (func x y)
    ...)

我想限制这些论点,以便:

  • x 是正整数
  • y 是一个小于或等于 x 的正整数

第一个约束显然是微不足道的,但有没有办法用Racket的合同系统设置第二个约束?

1 个答案:

答案 0 :(得分:5)

是。您想在使用->i合约组合器表达的Racket中使用依赖合同。您描述的功能合同如下所示:

   <android.support.design.widget.NavigationView
       android:id="@+id/nvTeste"
       android:layout_height="match_parent"
       android:layout_gravity="start"
       >
       <TextView
           android:layout_width="match_parent"
           android:text="apenas teste"
           android:layout_height="match_parent" />
   </android.support.design.widget.NavigationView>

以下是不恰当地应用与上述合同约定的功能时可能发生的错误的示例:

(->i ([x (and/c integer? positive?)]
      [y (x) (and/c integer? positive? (<=/c x))])
     [result any/c])

对于从属合同,需要对所有参数和结果进行命名,以便可以在其他子句中引用它们。第二个参数子句中的> (func 1 2) func: contract violation expected: (and/c integer? positive? (<=/c 1)) given: 2 in: the y argument of (->i ((x (and/c integer? positive?)) (y (x) (and/c integer? positive? (<=/c x)))) (result any/c)) contract from: (function func) 指定(x) 的合同取决于 y的值,因此您可以在x内使用x y的合同规范。

->i的完整语法可用in the documentation,其中包含许多其他功能。它还有一些例子,包括一个与你问题中的例子非常相似的例子。