- 3 minutes
Now that we’ve seen the relationship between types and functions, we’re going to start exploring datatypes more.
We’ve previously mentioned a type called
Bool, though we haven’t looked at it very carefully yet.
Bool represents the two values of Boolean logic,The
Bool type is named for George Boole. false and true. That’s all that’s in this set; there are only two possibilities in Boolean logic.
The datatype declaration for the Boolean type in Haskell looks like this:You do not need to enter this definition into
main.hs; it is already defined in the standard library.
data Bool = False | True
You might notice that it looks somewhat like a function declaration, with a name on the left side of an equals sign and its contents on the right. Here, the type name is given to the left of the equals sign, and what the set contains is on the right.
A datatype declaration is introduced by the keyword
data – this tells us that what we’re looking at is the definition of a type, not a function. Also notice that type names always begin with a capital letter, whereas function names are never capitalized.
The pipe means “or”. So a value of type
False, not both, and there are no other possibilities. This is a very small set, but it’s still useful. For example, a lot of really common functions return a Boolean output. Sometimes we just want a simple yes-or-no answer!
We’ll take a look at some examples in our REPL. We might say to GHCi: three is less than six?
λ> 3 < 6
And it tells us: that’s true! Three is indeed less than six.
Or we might say: “julie” equals “chris”?
λ> "julie" == "chris"
And that is false. Those two strings are not equal. Even though we believe in the equality of all humans, those two strings are not the same.
Or we might ask whether the letter j is an element of the string julie.
λ> elem 'j' "julie"
And that is true – there is a “j” in “julie”. Notice that when we are expressing the idea of a single character, we have to write it in single quotes, so that GHCi knows we are talking about a single character
'j' – this is a different idea than a string that contains a single character, which we would write as
"j". When we want a string, the type that can represent a bunch of characters together, then we use the double quotation marks.
Take a few minutes and experiment with typing some expressions using
== into your REPL.