Softwerkskammer

 

#Kapitel 3 - Zusammenfassung Teil 2

Hier folgt die Zusammenfassung der zweiten Hälfte des dritten Kapitels von "Real World Haskell".

Parameterized Types

  • introduce type variables into a type declaration
1
2
data Maybe a = Just a
             | Nothing

​- a is a type variable (like Java generics)

  • Maybe is a polymorphic/generic type
  • Maybe's with different type variables are distinct types: Maybe Int != Maybe Bool

Recursive Types

  • type which is defined in terms of itself

​```haskell
data List a = Cons a (List a)
| Nil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
- Nil: simples value of type List, may be used as parameter for Cons
 
 
​```haskell
data Tree a = Node a (Tree a) (Tree a)
              | Empty
              deriving (Show)
​```
 
​- binary tree is either a node with two children or an empty value
- children are themselves binary trees
 
# Reporting Errors
 
- standard function: error :: String -> a
- can be called if something went wrong
 
​​```haskell
mySecond :: [a] -> a
mySecond xs = if null (tail xs)
then error “list too short”
else head (tail xs)
​```
 
```haskell
:type error
error :: [Char] -> a
  • return type a just to possibly call it anywhere
  • actually it does not return a value like normal functions
  • instead it immediately aborts evaluation

Weakness

  • caller can’t distinguish between recoverable and error (no try/catch blocks possible)
  • error will always terminates evaluation
  • alternative: use Maybe to represent the possibility of an error

​## Reporting Errors with Maybe

1
2
3
4
5
safeSecond :: [a] -> Maybe a
safeSecond [] = Nothing
safeSecond xs = if null (tail xs)
then Nothing
else Just (head (tail xs))

​- caller can decide what to do with nullable

1
2
3
tidySecond :: [a] -> Maybe a
tidySecond (_:x:_) = Just x
tidySecond _ = Nothing

 

Wiki Links

Europaweite Veranstaltungen 2020
Jahreskalender von Konferenzen, Open Spaces, BarCamps und anderen Veranstaltungen