PasteRack.org
Paste # 46111
2014-09-22 09:13:28

Forked from paste # 67540.

Fork as a new paste.

Paste viewed 578 times.


Embed:

super generic function contract

  1. #lang racket/base
  2. (require racket/contract/base
  3.          racket/contract/combinator)
  4.  
  5. (define (gen->/c in/c in->out/c)
  6.   (define b->inp (contract-projection in/c))
  7.   (make-contract
  8.    #:first-order procedure?
  9.    #:projection
  10.    (lambda (b)
  11.      (define inp (b->inp (blame-swap b)))
  12.      (lambda (x)
  13.        (lambda args
  14.          (define args/c (inp args))
  15.          (call-with-values (lambda () (apply x args/c))
  16.            (lambda res
  17.              (define out/c (in->out/c args/c))
  18.              (define b->outp (contract-projection out/c))
  19.              (define outp (b->outp b))
  20.              (apply values (outp res)))))))))
  21.  
  22.   (require racket/list
  23.            rackunit)
  24.  
  25.   (define (f x)
  26.     (if (= x 7)
  27.       17
  28.       (apply values
  29.              (for/list ([i (in-range x)])
  30.                i))))
  31.  
  32.   (define f/c
  33.     (contract
  34.      (gen->/c (list/c number?)
  35.               (λ (l)
  36.                 (λ (out) (and (list? out)
  37.                               (= (length out) (first l))
  38.                               (andmap number? out)))))
  39.      f
  40.      'f
  41.      'test))
  42.  
  43.   (displayln "Example 1")
  44.   (f/c 5)
  45.   (displayln "Example 2")
  46.   (thread-wait (thread (λ () (f/c "foo"))))
  47.   (displayln "Example 3")
  48.   (thread-wait (thread (λ () (f/c 7))))

=>

Example 1

0

1

2

3

4

Example 2

f/c: contract violation

  expected: number?

  given: "foo"

  in: the 1st element of

      ...

      anonymous-contract

  contract from: f

  blaming: test

  context...:

   /home/stchang/plt601/racket/collects/racket/contract/private/blame.rkt:143:0: raise-blame-error16

   /home/stchang/plt601/racket/collects/racket/contract/private/misc.rkt:733:7

   /home/stchang/plt601/racket/collects/racket/contract/private/prop.rkt:257:10

Example 3

f/c: broke its contract

  promised: ???

  produced: '(17)

  in: anonymous-contract

  contract from: f

  blaming: f

  context...:

   /home/stchang/plt601/racket/collects/racket/contract/private/blame.rkt:143:0: raise-blame-error16