Type annotations, which are also sometimes called type signatures , are how Haskell lets you associate a type with an expression. Type annotations come after the name of a top-level function, a let or where binding, or after an expression. A type annotation starts with two colons ( :: ) followed by the type name.
Adding a type annotation to a binding in a source file can be done in two separate lines. For example, open a new source file and copy in the following example to create a new top-level binding named pi and give it the Float type:
| | pi :: Float |
| | pi = 3.14 |
If you have several bindings with the same type you can add them on multiple lines, or on a single line separated by commas:
| | one, two :: Int |
| | one = 1 |
| | two = 2 |
| | |
| | three :: Int |
| | three = 3 |
| | |
| | four :: Int |
| | four = 4 |
You can use this same style to assign type bindings in ghci , but in order to do so you’ll need to use :{ and :} to enter multiple lines. Note that you’ll need to do this even if you’ve enabled multiline mode automatically in ghci , since the type annotation by itself isn’t enough to tell ghci to start a multiline mode.
| | λ :{ |
| | > pi :: Float |
| | > pi = 3.14 |
| | > :} |
This is inconvenient, and so more often in ghci you’ll want to provide a type to the expression in a single line. To do that, enter the type on the right hand side of an assignment, after the expression. Try it out as in the following example:
| | λ pi = 3.14 :: Float |
You can also add type annotations to an expression without binding it to a name. Try out some of these examples to see it for yourself:
| | λ 1 :: Integer |
| | 1 |
| | λ [1,2] :: [ Float ] |
| | [1.0,2.0] |
| | λ "Hello" :: String |
| | "Hello" |
You aren’t limited to just adding type annotations for top-level bindings and expressions in ghci . You can add type annotations to let and where bindings too. Try copying this example into a source file and testing it from ghci :
| | calculateTotalCost basePrice = |
| | let |
| | priceWithServiceFee :: Int |
| | priceWithServiceFee = basePrice + 1 |
| | customaryTip = 7 :: Int |
| | in priceWithServiceFee + customaryTip |
In this example, you can see both styles of type annotations being used inside of a let binding. In the case of priceWithServiceFee , you are adding an annotation to the variable, and in the case of customaryTip , you’re assigning the variable a value that includes a type annotation. For now, we’ve skipped over adding a type for calculateTotalCost ; in the next section, you’ll learn how to write function types.