Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Product and Sum types

Product and Sum types

Presentation based on the post "Why Sum Types Matter in Haskell" https://medium.com/@willkurt/why-sum-types-matter-in-haskell-ba2c1ab4e372

2fa9df92d8d7eba3e17207c86f953be3?s=128

Filippo Vitale

April 24, 2018
Tweet

Transcript

  1. Sum types in Haskell @filippovitale × @mwotton

  2. None
  3. struct author_name { char *first_name; char *last_name; }; struct book

    { author_name author; char *isbn; char *title; int year_published; double price; };
  4. data AuthorName = AuthorName {firstName :: String ,lastName :: String

    } data Book = Book {author :: AuthorName ,isbn :: String ,title :: String ,year :: Int ,price :: Double }
  5. // 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; }
  6. Sum types: Combining Types with ‘or’

  7. 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; }
  8. 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
  9. data CollectibleToy = CollectibleToy { name :: String , descrption

    :: String , toyPrice :: Double} data StoreItem = BookItem Book | RecordItem VinylRecord | ToyItem CollectibleToy
  10. 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