1 Functional Programming Lecture 6 - Algebraic Data Types.

Slides:



Advertisements
Similar presentations
Modelling & Datatypes John Hughes. Software Software = Programs + Data.
Advertisements

Haskell Lets review some of the Haskell concepts you have been learning on your own. The answers are included, but try it yourself first.
Modern Programming Languages, 2nd ed.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
Peter Fritzson 1 MetaModelica for Meta-Modeling and Model Transformations Peter Fritzson, Adrian Pop, Peter Aronsson OpenModelica Course at INRIA, 2006.
Extended Static Checking for Haskell (ESC/Haskell) Dana N. Xu University of Cambridge advised by Simon Peyton Jones Microsoft Research, Cambridge.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Exercises – don’t use built in functions for these as we want the practice Write a recursive function to add up all the numbers in a list "flatten" a list.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Com Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Defining new types of data. Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes – enumerated.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Comp 205: Comparative Programming Languages User-Defined Types Enumerated types Parameterised types Recursive types Lecture notes, exercises, etc., can.
Last Time Introduction Course Logistics Introduction to ML Base Types Tuples and Records Functions & Polymorphism See Harper ’ s Intro to ML.
Advanced Programming Andrew Black and Tim Sheard Lecture 4 Intro to Haskell.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
Data Types.
Haskell Chapter 3, Part I. Pattern Matching  Pattern matching with tuples  Pattern matching with list comprehensions  As-patterns.
1 COMP313A Programming Languages Functional Programming (7)
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Operators, Functions and Modules1 Pattern Matching & Recursion.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Sound Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen Chalmers University of Technology.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
Overview of the Haskell 98 Programming Language
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Functional Programming Lecture 5 - Tuples. Packaging several values together Sometimes you need to package up several values into a single object –A function.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Chapter SevenModern Programming Languages1 A Second Look At ML.
1 Static Contract Checking for Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
Functional Programming Lecture 3 - Lists Muffy Calder.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Haskell Chapter 7.
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Haskell Chapter 2.
Lecture 2:Data Types, Functional Patterns, Recursion, Polymorphism
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
Types and Classes in Haskell
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
Records and Type Classes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Review Previously User-defined data types: records, variants
Records and Type Classes
Presentation transcript:

1 Functional Programming Lecture 6 - Algebraic Data Types

2 Algebraic Data Types A powerful mechanism for defining your own data types. All other types in Haskell can be defined using algebraic data types. We will start with simplest cases and work toward the most complicated.

3 Enumerated Types Example: data Colour = Red | Green | Blue data is a keyword - defines an algebraic data type. Colour is the type name. Red, Green, Blue are constructors. Red :: Colour, Green ::Colour, etc. Red:: Colour Green :: Colour The type name and constructors must begin with an upper case letter. Variable must begin with lower case letter.

4 Pattern Matching You can pattern match on this enumerated type. Example: value :: Colour -> Int value Red = 15 value Green = 42 value Blue = 5 In general, define equations by function-name pattern = expression pattern is a constructor. data Day = Mon|Tues.. weekend :: Day -> Bool weekend d = (d==Sat) || (d==Sun)

5 Deriving Often when you define a new data type, you also need to define a function that shows it. (show -- convert to string, for printing) Example showColour :: Colour -> String showColour Red = “Red” showColour Blue = “Blue” …... showInt :: Int -> String showInt 5 => “5”

6 deriving Show data Colour = Red | Blue | Green deriving Show deriving Show tells the compiler automatically to define show :: Colour -> String Example: let c = Blue in “The answer is” ++ c ++ “\n” wrong! let c = Blue in “The answer is” ++ (show c) ++ “\n” today :: Colour -> String today c = “the sky is “++ (show c) ++ “.”

7 Example: The Bool Type data Bool = False | True deriving Show This is a built-in declaration in Haskell. False, True are the boolean constants - constructors of type Bool.

8 Data Fields Example: data Thing = Item Int String deriving Show A value of type Thing consists of a constructor Item (indicating what it is), a data field containing an Int, and another field containing a String. u :: Int w :: String Item u w :: Thing Examples x, y :: Thing x = Item 3 “small” y = Item (2+3) (str++”\n”) show x => “Item 3 small”

9 Polymorphic Data Fields Allow type a (where a is a type variable) instead of a specific type like Int. Entire data type has type parameter a. data Object a = Obj Int a x = Obj 15 True :: Object Bool y = Obj :: Object Int z = Obj 39 “Hello” :: Object String compare :: (Eq a) => Object a -> Object a -> Bool compare (Obj i x) (Obj j y) = (i ==j) && (x == y) Examples compare (Obj 27 13) (Obj 27 6) => compare (Obj 27 13) (Obj 27 “hello”) => compare1 :: Object a -> Object a -> Bool compare1 (Obj i _) (Obj j _) = (i ==j)

10 Example: Tuple Types data Pairs a b = Pair a b data Triples a b c = Triple a b c data Tuple4s a b c d = Tuple4 a b c d ……. The builtin tuple types behave essentially like this, except they have a special syntax with (,,,) So, Pair 2 3 :: Pairs Int Int (2,3) :: (Int,Int)

11 Constructors and Union Types There could be several different cases each case has its own constructor and can have different fields. Example data PhoneNumber = LocalPhone Int | BritishPhone Int Int | InternationalPhone Int Int Int Localphone :: PhoneNumber BritishPhone :: PhoneNumber InternationalPhone :: PhoneNumber

12 Union Types data Course = FP String String Room | DSA String [String] [Room] FP “Calder” “Haskell” lect2 ::Course DSA “Miller” [“Ada”,”Java”] [lec4,lec5] ::Course

13 Computations that might fail Sometimes a computation may succeed or fail but the program should deal with failure, instead of crashing. Example average :: [Double] -> Double average xs = sum xs / fromInt (length xs) average [4,12] => 8.0 average [ ] => divide by 0 error - crash! Also, head []

14 The Maybe type data Maybe a = Just a | Nothing Represents result of a computation that maybe gives you a value of type a, but could give you nothing. Normal values of a Nothing Just 0 Nothing Just 1 Just 2 Just 3 Just 4 Just 5 Just 6 ….. Maybe Int

15 The Maybe type average :: [Double] -> Maybe Double average [ ] = Nothing average xs = Just (sum xs / length xs) head :: [a] -> Maybe a head [] = Nothing head (x:xs) = Just x f xs ys = x : ys where Just x = head xs What is type of f? [a] -> [a] -> [a] Why?

16 Recursive Types A type T which has some data fields of type T. Example data T = T0 String | T1 Int T s ::String x :: Int t :: T TO s :: T T1 x t :: T x, y, z :: T x = T0 “aardvark” y = T1 31 (T0 “cat”) z = T1 17 (T1 86 (T0 “dog”))

17 Integer Lists data List = Empty | Cons Int List All equivalent representations! Cons 3 (Cons 4 (Cons 1 Empty)) 3:(4:(1:Empty)) [3,4,1]