mirror of
https://github.com/thma/WhyHaskellMatters.git
synced 2024-09-11 13:46:11 +03:00
start to work on type classes
This commit is contained in:
parent
660527e248
commit
e88d9fefb8
30
README.md
30
README.md
@ -1157,8 +1157,34 @@ data Severity = Low | Middle | High deriving (Eq)
|
||||
data PairStatusSeverity = PSS Status Severity deriving (Eq)
|
||||
```
|
||||
|
||||
This automatic deriving of type class instances works for many cases and reduces the need to write
|
||||
boilerplate code.
|
||||
This automatic deriving of type class instances works for many cases and reduces a lof of boilerplate code.
|
||||
|
||||
### Read and Show
|
||||
|
||||
Two other quite useful type classes are `Read` and `Show`.
|
||||
|
||||
`Show` provides a function `show` with the following type signature:
|
||||
|
||||
```haskell
|
||||
show :: Show a => a -> String
|
||||
```
|
||||
|
||||
This means that any type implementing `Show` can be converted (or *marshalled*) into a `String` representation.
|
||||
Creation of a `Show` instance can be achieved by adding a `deriving (Show)` clause to the type declaration.
|
||||
|
||||
```haskell
|
||||
data PairStatusSeverity = PSS Status Severity deriving (Show)
|
||||
|
||||
λ> show (PSS Green Low)
|
||||
"PSS Green Low"
|
||||
```
|
||||
|
||||
The `Read` type class is used to do the opposite: *unmarshalling* data from a String with the function `read`:
|
||||
|
||||
```haskell
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -4,17 +4,17 @@ module AlgebraicDataTypes where
|
||||
import Control.Monad ((>=>))
|
||||
|
||||
-- a simple sum type
|
||||
data Status = Green | Yellow | Red --deriving (Eq, Show)
|
||||
data Severity = Low | Middle | High --deriving (Eq, Show)
|
||||
data Status = Green | Yellow | Red deriving (Show, Read)
|
||||
data Severity = Low | Middle | High deriving (Show, Read)
|
||||
|
||||
severity :: Status -> Severity
|
||||
severity Green = Low
|
||||
severity Yellow = Middle
|
||||
severity Red = High
|
||||
|
||||
data StatusSeverityTuple = SST Status Severity --deriving (Eq, Show)
|
||||
data StatusSeverityTuple = SST Status Severity deriving (Show, Read)
|
||||
|
||||
data PairStatusSeverity = PSS Status Severity
|
||||
data PairStatusSeverity = PSS Status Severity deriving (Show, Read)
|
||||
|
||||
-- a simple product type
|
||||
data Pair = P Status Severity --deriving (Show)
|
||||
|
Loading…
Reference in New Issue
Block a user