Search code examples
racketoption-typecontract

How to specify optional argument within contract-out clause in Racket?


Given I have some function with signature like following

(define (my-method a [b 100])
    (/ a b)
 )

, how am I supposed to specify such signature in contract-out?

Using

(contract-out
          [my-method (-> number? number? number?)])

and then in another module

(my-method 200)

is not helping as it emits error saying "contract violation, received: 1 arguments, expected: 2 non-keyword arguments". And I guess I cannot just combine two contracts with and without optional using or/c.


Solution

  • Use ->* and list mandatory arguments first (in a group), then optional arguments (in a second group), and then the result. There are more advanced options too; see the docs.

    (contract-out
      [my-method
       (->* [number?]  ;; 1 mandatory argument
            [number?]  ;; 1 optional argument
            number?)])
    

    This is covered in the Contracts chapter of Racket Guide, on the section named Optional Arguments.