From 28291764fa543497198ed737b109c80c79c51b2c Mon Sep 17 00:00:00 2001 From: Edoardo La Greca Date: Sat, 21 Jun 2025 15:55:29 +0200 Subject: add lecture 2 notes --- lec02/notes.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 lec02/notes.md (limited to 'lec02/notes.md') diff --git a/lec02/notes.md b/lec02/notes.md new file mode 100644 index 0000000..7420f92 --- /dev/null +++ b/lec02/notes.md @@ -0,0 +1,38 @@ +# Lecture 2: Algebraic data types + +## Enumeration types + + data Thing = Shoe + | Ship + | SealingWax + | Cabbage + | King + derivating Show + +The example above is a **type declaration**. The new type is called `Thing` and it has 5 **data constructors** (`Shoe`, `Ship`, etc.). A type's constructors are the only values for that type. + +The line that says `deriving Show` is a special instruction that tells the GHC to automatically generate default code for converting a `Thing` to `String`. + + Shoe :: Thing + Shoe = Shoe + + listO'Things :: [Thing] + listO'Things = [Show, SealingWax, King, Cabbage, King] + +Functions on enumeration types can be written using pattern-matching. + + isSmall :: Thing -> Bool + isSmall Show = True + isSmall Ship = False + isSmall SealingWax = True + isSmall Cabbage = True + isSmall King = False + +Since function clauses are checked from top to bottom, `isSmall` can be rewritten like this: + + isSmall2 :: Thing -> Bool + isSmall2 Ship = False + isSmall2 King = False + isSmall2 _ = True + +## Beyond enumeration -- cgit v1.2.3