【问题标题】:Racket parametric contracts errors球拍参数合同错误
【发布时间】:2020-09-07 02:32:38
【问题描述】:

我已经开始学习合同,我有这样的程序:

(define/contract (foldr-map f a xs)
  foldr-map/c
  (define (it a xs ys)
    (if (null? xs)
        (cons ys a)
        (let* [(p (it a (cdr xs) ys))
              (fc (f (car xs) (cdr p)))]
          (cons (cons (car fc) (car p)) (cdr fc)))))

  (it a xs null))

(foldr-map (lambda (x a) (cons a (+ a x))) 0 `(1 2 3))

我将flodr-map/c 合同定义为:


(define foldr-map/c
  (parametric->/c [x a] (->
                         (-> x a (cons/c a number?))
                         a
                         (listof x)
                         (cons/c (listof a) a))))

但我看到这样的错误:

foldr-map: broke its own contract
  promised: a
  produced: 3
  in: the 2nd argument of
      the 1st argument of
      (parametric->/c
       (x a)
       (->
        (-> x a (cons/c a number?))
        a
        (listof x)
        (cons/c (listof a) a)))
  contract from: (function foldr-map)
  blaming: (function foldr-map)
   (assuming the contract is correct)

我知道程序运行正常,所以合同肯定是错误的。该过程接受参数f,它是一个函数。

合约有2个参数:

  • x 是列表 xs 的一个元素
  • a 是一个累加器

当我将合同更改为:

(define foldr-map/c
  (parametric->/c [x a] (->
                         (-> x number? (cons/c number? number?))
                         a
                         (listof x)
                         (cons/c (listof a) a))))

我收到这样的错误:

foldr-map: broke its own contract
  promised: number?
  produced: #<a>
  in: the 2nd argument of
      the 1st argument of
      (parametric->/c
       (x a)
       (->
        (-> x number? (cons/c number? number?))
        a
        (listof x)
        (cons/c (listof a) a)))
  contract from: (function foldr-map)
  blaming: (function foldr-map)
   (assuming the contract is correct)

所以此时我迷路了。

【问题讨论】:

    标签: functional-programming scheme lisp racket


    【解决方案1】:

    我找到了解决办法:

    (define foldr-map/c
      (parametric->/c [x a] (->
                             (-> x a (cons/c a a))
                             a
                             (listof x)
                             (cons/c (listof a) a))))
    

    这是有道理的,而且看起来有点明显,但需要相当长的调试时间才能弄明白。

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多