Hey! I am currently working my way through the Racket guide and I am struggling a bit to grok unconstrained-domain->
in the example 7.3 Contracts on Functions in General.
I'll paste the example here and work through my understanding thus far and hopefully someone can help fill in the gaps.
(define (n-step proc inits)
(let ([inc (apply proc inits)])
(when inc
(n-step proc (map (λ (x) (+ x inc)) inits)))))
(provide (contract-out [n-step
(->i ([proc
(inits)
(and/c (unconstrained-domain-> (or/c #f number?))
(λ (f) (procedure-arity-includes? f (length inits))))]
[inits (listof number?)])
()
any)]))
I want to export n-step
with this contract. We use the ->i
to handle optional parameters, we have none so this could be ->
? Or, do I need ->i
to enable this syntactic form? proc
is the first parameter of the function and I don't quite understand the (inits)
syntax that follows it. Is this stating that proc
takes a single argument inits
? It can't (right?) otherwise we wouldn't need to check the arity matches the length of inits. Everything beyond that makes sense.
I took this example and attempted to write a contract with unconstrained-domain->
for the following stupid example,
(define (increment x)
(+ x 1))
(provide (contract-out [increment
(->i ([x (and/c (unconstrained-domain-> number?) (λ (y) (> y 2)))]) () any)]))
i.e. increment will only work for numbers greater than 2. I understand this is silly, but I wanted to test my understanding. I guess ideally it would also check that y
is a number?
. The error I get from this is,
> (increment 1)
increment: contract violation
expected: a procedure
given: 1
in: the 1st conjunct of
the x argument of
(->i
((x
(and/c
(unconstrained-domain-> number?)
...-guide/chapter7.rkt:237:73)))
any)
contract from:
/home/chiroptical/programming/racket/the-racket-guide/chapter7.rkt
blaming: top-level
(assuming the contract is correct)
at: /home/chiroptical/programming/racket/the-racket-guide/chapter7.rkt:236:24
[,bt for context]
It is entirely possible my syntax is just wrong.