typesfunctional-programmingsmlparametric-polymorphism

How to declare a type that matches any function in Standard ML?


I'm trying to declare a record type that has two entries, one named id that is a string, and another named algorithm that can be any function.

According to what I've investigated, I need to use parametric polymorphism to declare the type of the algorithm entry in the record. Something like this:

type subject = {algorithm: 'a -> 'b, id: string}

But this yields the following error

subject.sml:1: error: 'a has not been declared in type declaration
subject.sml:1: error: 'b has not been declared in type declaration

How can one declare a function type that matches any function? Is using "alpha" and "beta" types the correct way to do this? If so, how does one refer to these types? If not, how is this achieved? Is there a type like bool or real that just means "all functions" or "any function"?


Solution

  • There's no type that means "any function"; for example, int -> real and string -> bool are completely separate types, and there's no way to create a type that's ambiguous between the two of them.

    However, you can create a type function that takes two types and returns the appropriate record type:

    type ('a, 'b) subject = {algorithm: 'a -> 'b, id: string}
    

    After the above declaration, (int, real) subject (for example) will mean {algorithm: int -> real, id: string}.

    Is using "alpha" and "beta" types the correct way to do this? If so, how does one refer to these types?

    Yes — "alpha" and "beta" are just how you pronounce 'a and 'b, respectively. They're not a separate concept. :-)