Slide 1

Slide 1 text

Sum types in Haskell @filippovitale × @mwotton

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

struct author_name { char *first_name; char *last_name; }; struct book { author_name author; char *isbn; char *title; int year_published; double price; };

Slide 4

Slide 4 text

data AuthorName = AuthorName {firstName :: String ,lastName :: String } data Book = Book {author :: AuthorName ,isbn :: String ,title :: String ,year :: Int ,price :: Double }

Slide 5

Slide 5 text

// The curse of product types: Hierarchical design public class StoreItem { String title; int yearPublished; double price; } public class Book extends StoreItem { Author author; String isbn; } public class VinylRecord extends StoreItem { String artist; }

Slide 6

Slide 6 text

Sum types: Combining Types with ‘or’

Slide 7

Slide 7 text

data Name = Name FirstName LastName | NameWithMiddle FirstName MiddleName LastName | TwoInitialsWithLast Char Char LastName | FirstNameWithTwoInits FirstName Char Char public class Name { String firstName; String lastName; String middleName; char firstInitial; char middleInitial; char lastInitial; }

Slide 8

Slide 8 text

data Book = Book {author :: Creator , isbn :: String , bookTitle :: String , bookYear :: Int , bookPrice :: Double} data VinylRecord = VinylRecord { artist :: Creator , recordTitle :: String , recordYear :: Int , recordPrice :: Double} data StoreItem = BookItem Book | RecordItem VinylRecord

Slide 9

Slide 9 text

data CollectibleToy = CollectibleToy { name :: String , descrption :: String , toyPrice :: Double} data StoreItem = BookItem Book | RecordItem VinylRecord | ToyItem CollectibleToy

Slide 10

Slide 10 text

price :: StoreItem -> Double price (BookItem book) = bookPrice book price (RecordItem record) = recordPrice record price (ToyItem toy) = toyPrice toy https://medium.com/@willkurt/why-sum-types-matter-in-haskell-ba2c1ab4e372