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

Filippo Vitale

April 24, 2018
Tweet

More Decks by Filippo Vitale

Other Decks in Programming

Transcript

  1. struct author_name { char *first_name; char *last_name; }; struct book

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

    } data Book = Book {author :: AuthorName ,isbn :: String ,title :: String ,year :: Int ,price :: Double }
  3. // 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; }
  4. 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; }
  5. 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
  6. data CollectibleToy = CollectibleToy { name :: String , descrption

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