rackettyped-racket

Typed/Racket - How do I make this function work, keep getting TypeChecker errors


Having

(: f (-> Procedure (Pairof Integer Integer) Boolean))
   (define (f comparator pair)
      (comparator (first pair) (second pair)))

in TypedRacket, how can I make this function work? The function is supposed to work like this:

(f = '(1 2)) >>>> false.
(f > '(4 2)) >>>> true.

I get following errors:

Type Checker: Polymorphic function first could not be applied to arguments
Type Checker: Polymorphic function second could not be applied to arguments
Type Checker: cannot apply a function with unknown arity

So probably it is the function definition which causes this error but how can I fix this?


Solution

  • Here is a definition that does work for your examples:

    (: f (-> (-> Integer Integer Boolean) (Listof Integer) Boolean))
    (define (f comparator pair)
      (comparator (first pair) (second pair)))
    
    (f = '(1 2))   ; => #f
    
    (f > '(4 2))   ; => #t
    

    You must define the type of the first parameter as function from two integers to a boolean, and the second argument as a list (since you used a list in the call of the function).

    This is a simple definition, just to start working with types. Than you can change it to apply the function to values with more general types, like Number instead of Integer, polymorphic functions, etc.