Static Type Check
We also said that Haskell is a statically-typed language, which means that each expression type is known at compilation time instead of run-time. This makes Haskell very reliable – if we successfully compile our program, we can be sure that no type errors will occur. This benefit does come at a cost of increased compilation time, and doing any changes to our program requires us to re-compile it.
Another feature of Haskell is type inference, which means that Haskell can automatically interpret types of expressions. This can make our code more concise, but it is still encouraged to explicitly specify the types when we define functions, i.e. to write functions by also including their type signatures. For our previous function triple
, we could add a type signature to it in our Practice.hs
:
triple :: Int -> Int
reads as "triple
is a function that takes in one argument of the type Int
and produces a result of a type Int
". Now that we have altered our module code, we need to reload the practice module in order to apply the changes in GHCi:
But what happens if we try to apply our triple
function to a floating-point number?
We get a type error because we strictly defined the function as one that takes in an Int
as its only argument, but we passed in a floating-point number.
Polymorphism
So how can we make our function accept both Int
and Float
? To do that, we can use Haskell's polymorphism and specify a polymorphic type of Num a
(an overloaded type specified with a type class - more on those on the next page), which supports both integer and floating-point numbers:
The line triple :: Num a => a -> a
now reads as "triple
is a function that takes in one argument of type a
and gives a result of type a
where the type of a
is Num
". So here we see an example of polymorphism where we can work with different types for the same function argument. Note that we use the variable named a
as a placeholder for the type class Num
, but it could be any valid name starting with a lowercase character.
Last updated