schemeracketplai

How to give a specific type of function as a parameter in Racket/Plait?


I am writing a function that takes in a function and a list as parameters. The parameter function and the list must have the same type of values. How do I ensure that?

I have tried:

(define ( (func -> 'a) [lst : (Typeof 'a)])
     ....)

However, I have not been able to get it working. I have also gone through the plait tutorial but didn't find anything relevant.

Is it even possible to have a function that accepts a function of a specific return type?


Solution

  • Is this what you are looking for?

    (define f : (('a -> 'a) (listof 'a) -> string)
      (lambda (func lst) "hello"))
    

    Then:

    (f (lambda ([x : number]) x) (list 1))
    

    type checks, but:

    (f (lambda ([x : number]) x) (list "foo"))
    

    doesn't type check, because 'a is unified with string (from "foo"), but is also unified with number (from x), so a type mismatch occurs.

    Note that

    (define f : (('a -> 'a) (listof 'a) -> string)
      (lambda (func lst) "hello"))
    

    and

    (define (f [func : ('a -> 'a)] [lst : (listof 'a)]) : string
      "hello")
    

    are different. In the former, 'a refers to the same type variable across arguments. In the latter, func's 'a and lst's 'a are different. Therefore, in the latter, the following expression type checks:

    (f (lambda ([x : number]) x) (list "foo"))