Mind map
Types and Typeclasses
Map content
Types and Typeclasses
how to make our own and how to put them to work
use the data keyword to define a type
- data Bool = False | True
- The part before the = denotes the type
- The parts after the = are value constructors
- Bool can have a value of True or False
- Both the type name and the value constructors have to be capital cased.
- Using data type
- data Shape = Circle Float Float Float | Rectangle Float Float Float Float
- The Circle value constructor has three fields
- The Rectangle value constructor has four fields
- surface :: Shape -> Float surface (Circle _ _ r) = pi * r ^ 2 surface (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1)
- the function takes a shape and returns a float
- we can pattern match against constructors
- the function takes a shape and returns a float
- You can export your data types in your modules. for it, separated by commas.
- To do that, just write your type along with the functions you are exporting and then add some parentheses and in them specify the value constructors that you want to export
- If you want to export all the value constructors for a given type, just write ...
- module Shapes ( Point(..) , Shape(..) , surface , nudge , baseCircle , baseRect ) where
- To do that, just write your type along with the functions you are exporting and then add some parentheses and in them specify the value constructors that you want to export
- data Shape = Circle Float Float Float | Rectangle Float Float Float Float
- deriving (Show)
- at the end of a data declaration, Haskell automagically makes that type part of the Show typeclass
- in witch way we can print the object like toString in java
- data Point = Point Float Float deriving (Show)
- at the end of a data declaration, Haskell automagically makes that type part of the Show typeclass
- data Bool = False | True
Record syntax
- What if we want to create a function to get seperate info from a person
- data Person = Person { firstName :: String , lastName :: String , age :: Int , height :: Float , phoneNumber :: String , flavor :: String } deriving (Show)
- we use curly brackets
- First we write the name of the field
- then we write a double colon ::
- and then we specify the type
- then we write a double colon ::
- First we write the name of the field
- What if we want to create a function to get seperate info from a person
Type parameters
- A value constructor can take some values parameters and then produce a new value
- data Maybe a = Nothing | Just a
- The a here is the type parameter
- Depending on what we want this data type to hold when it's not Nothing
- The a here is the type parameter
- data Maybe a = Nothing | Just a
- A value constructor can take some values parameters and then produce a new value
Information
- Description
- Mind Map on Types and Typeclasses, created by sixto alberto becerra reslen on 03/04/2020.
- Created by
- sixto alberto becerra reslen
- Views
- 0
- Rating