Where f behaves in some specific ways for certain types. In other words, you can read the type a -> a -> aĪs a promise that a function with this type will work no matter what type the caller chooses.Īnother implementation we could imagine is something like f a1 a2 = case (typeOf a1) of Here we, the implementors, have tried to choose a specific type (namely, Bool), but we may be given String, or Int, or even some type defined by someone using f, which we can’t possibly know about in advance. The reason this doesn’t work is that the caller of a polymorphic function gets to choose the type. In the second argument of `(&)', namely `y' ![]() The core idea is to allow programmers to use a wildcard type when defining data structures that can later be filled with any type. The type signature for f :: a -> a -> a at. Parametric polymorphism This is a pretty common technique in many languages, albeit better known as 'Generics'. ![]() The syntax is valid, at least, but it does not type check. We consider parametric polymorphism in more detail. Examples include polymorphic functions in ML, or generics in Java 5. Remember that a is a type variable which can stand for any type. Parametric polymorphism refers to code that is written without knowledge of the actual type of the arguments the code is parametric in the type of the parameters. This turns out to have some interesting implications for both programmers and users of polymorphic functions. These are different functions, and they can act in totally different ways, but the compiler or interpreter chooses the appropriate one depending on the context. + : int -> int -> int and + : float -> float -> float in SML. Essentially, this means that polymorphic functions must work uniformly for any input type. Ad-hoc polymorphism usually refers to being able to declare the same name (usually a function) with different types, e.g. Haskell’s particular brand of polymorphism is known as parametric polymorphism.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |