Just like we can't write a function with a type declaration of True -> Int. We couldn't write a type declaration of Circle -> Float because Circle is not a type, Shape is. It says that the function takes a shape and returns a float. The first notable thing here is the type declaration. Surface (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1) Who would have thought? Let's make a function that takes a shape and returns its surface. Rectangle :: Float -> Float -> Float -> Float -> ShapeĬool, so value constructors are functions like everything else. Let's take a look at the type signatures for these two value constructors.Ĭircle :: Float -> Float -> Float -> Shape Value constructors are actually functions that ultimately return a value of a data type. Now when I say fields, I actually mean parameters. The first two are the coordinates to its upper left corner and the second two are coordinates to its lower right one. The Rectangle value constructor has four fields which accept floats. Here, the first two fields are the coordinates of its center, the third one its radius. So when we write a value constructor, we can optionally add some types after it and those types define the values it will contain. The Circle value constructor has three fields, which take floats. Here it is:ĭata Shape = Circle Float Float Float | Rectangle Float Float Float Float Let's say that a shape can be a circle or a rectangle. A better solution would be to make our own type to represent a shape. Sounds OK, but those could also represent a 3D vector or anything else. A circle could be denoted as (43.1, 55.0, 10.4) where the first and second fields are the coordinates of the circle's center and the third field is the radius. Now, let's think about how we would represent a shape in Haskell. It's not actually defined like this, the ellipses are here because we omitted a heapload of numbers, so this is just for illustrative purposes.
The first and last value constructors are the minimum and maximum possible values of Int. In a similar fashion, we can think of the Int type as being defined like this:ĭata Int = -2147483648 | -2147483647 |. Both the type name and the value constructors have to be capital cased. So we can read this as: the Bool type can have a value of True or False. They specify the different values that this type can have. The parts after the = are value constructors. The part before the = denotes the type, which is Bool. Let's see how the Bool type is defined in the standard library.ĭata means that we're defining a new data type. But how do we make our own? Well, one way is to use the data keyword to define a type. So far, we've run into a lot of data types.
Type to learn 3.com how to#
In this chapter, we'll learn how to make our own and how to put them to work! Algebraic data types intro In the previous chapters, we covered some existing Haskell types and typeclasses.