Monday, June 06, 2016

[awlyiqda] Type signatures asking for more than they need

A type signature to a function creates the requirement that an argument passed to the function have a specified type.  However, operationally, the function only needs for the argument to have certain operations (other functions) defined on it.

Type classes in Haskell provide a means for a function to be polymorphic, accepting many different types, with the type class defining the set of fundamental functions (methods) available.  However, even type classes may be too much: a function might require only a subset of the fundamental functions.

Duck typing is a much "looser" way of addressing this same problem.  Previous thoughts on this problem.

Sometimes, even though all the operations a function needs might be defined on a type, we want to use the type signature of the function to restrict what it can be called on.  The "explode" method might be defined for both firecrackers and nuclear weapons, but we might never want to accidentally pass a nuclear weapon to a certain function.

There is also a software engineering, and somewhat social, aspect to this problem.  Even though today's implementation of a function might not require some method of a type class, tomorrow's improved implementation might.  Declaring the type signature to be more than minimal is like making a reservation for future demands of functionality in the arguments.  Making such a reservation forces all other software calling that function to provide that functionality, even though it isn't currently used.  A type signature therefore represents a battle over a property line: who "owns" the right to decide what functionality an object should have?

1 comment :

Twan van Laarhoven said...

Types and type classes often also come with implicit laws. For instance (+) and (*) commute. If you have an instance of (Num a), then you know that this law holds, but if you only have an appropriate (+) and (*) then you don't. So the functions "f x y z = x * (y + z)" and "g x y z = x * y + x * z" might be different.

This is similar to your 'explode' example. Firecrackers satisfy a law that exploding them doesn't destroy the world, nuclear weapons don't.