Instructor: First, let's write a function declaration and give it a type of int. Now, let's write the function itself, myTypes = 1. Let's explain a little bit about the type declaration. We have myTypes, two colons, and then the word int. You can think of the two colons as the introduction of what type your function is. In this scenario, our function has a type of integer.
Let's change the value of myTypes to 1.0The right-hand side of our screen is the output of the compiler. When our program compiled, the compiler noticed there was an error. It could not match type number with type int. Because we changed our value from 1, which was an integer, to 1.0which is a number, the compiler showed us the error.
Let's try another one. This time, we'll change our value to a string. As expected, the compiler's picked up an error. Let's make this right by changing our type declaration to string. Now, the compiler has no errors.
Let's change our type declaration to Boolean. As you can see, the compiler picks up an error. Now, we'll change the actual value to be true. Once again, everything back to normal, and the code compiles.
It should be said that a compiler doesn't actually require these type declarations, but let's demonstrate why they are used in our next example. We're going to make a new function called addMe. Let's start our declaration. We'd write int > int > int. This type declaration would actually be read int to int to int.
What does that mean? It takes an integer, another integer, and it returns an integer. Let me demonstrate that for you by writing addMe a b = a + b. The first int in our type declaration would be the a, the second int would be the b, and the returning int would be a + b.
The way I simplify it in my mind is I look at the last type, and I think, "That's my return type of my function. And then, whatever values to the left of that are the types of the inputs to your function." In this case, we have two types, we have two inputs, a and b.
Let's see this function in action. We'll write addMe 5 and 6, which results in 11. This is exactly what I would expect, because we're adding a and b, which is 5 + 6. Now, let's make our second value a string of a. Straightaway, you'll see the compiler show an error. It could not match the type string with int.
Let's switch that back. We'll have addMe 5 and 5, which returns the expected 10. As I mentioned before, technically, the type declarations aren't needed. If you didn't type them in, the compiler would infer them for you. What it is great for is to let you know in the future exactly what your function does. For this instance, we expect two ints, and we'll return an int.
There you have it, a simple introduction to types in PureScript.