Com2010 - Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

Haskell user defined types data Temp = Cold|Hot|Warm deriving (Show,Eq, Ord, Enum) -- to enable printing to screen -- comparing for equality -- comparison.
9-Jun-14 Enum s (and a review of switch statements)
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Enumerated data type & typedef. Enumerated Data Type An enumeration consists of a set of named integer constants. An enumeration type declaration gives.
ENUMERATED, typedef. ENUMERATED DATA TYPES An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name.
Line Efficiency     Percentage Month Today’s Date
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
Comp 205: Comparative Programming Languages User-Defined Types Enumerated types Parameterised types Recursive types Lecture notes, exercises, etc., can.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Composite types Cartesian products –tuples, records, structures disjoint unions –union, discriminated or variant records mappings –arrays, functions recursive.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
1 Chapter 10 Various Topics User defined Types Enumerated Types Type Casting Syntactic Sugar Type Coercion.
© M. Winter COSC 4P41 – Functional Programming Enumerated types data Temp = Cold | Hot data Season= Spring | Summer | Autumn | Winter weather ::
Com Functional Programming Higher Order Functions and Computation Patterns (I) Marian Gheorghe Lecture 10 Module homepage Mole &
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Com Functional Programming Higher Order Functions and Computation Patterns (II) Marian Gheorghe Lecture 11 Module homepage Mole &
9. Types Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Data Types data type:a collection of.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Com Functional Programming Regular Expressions and Abstract Data Types Marian Gheorghe Lecture 14 Module homepage Mole &
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Com Functional Programming Lazy Evaluation Marian Gheorghe Lecture 13 Module homepage Mole & ©University of Sheffieldcom2010.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Chapter SevenModern Programming Languages1 A Second Look At ML.
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.
Recursion Higher Order Functions CSCE 314 Spring 2016.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
String is a synonym for the type [Char].
Jan 2016 Solar Lunar Data.
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Haskell Chapter 2.
Functions and patterns
The 6 steps of data collection:
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Gantt Chart Enter Year Here Activities Jan Feb Mar Apr May Jun Jul Aug
Types and Classes in Haskell
PROGRAMMING IN HASKELL
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Defining New Data Types
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
Text for section 1 1 Text for section 2 2 Text for section 3 3
PROGRAMMING IN HASKELL
Presentation transcript:

Com Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of Sheffieldcom2010

19. Algebraic data types 19.1 What is an algebraic type? 19.2 Algebraic Types, More Systematically Enumeration Product Nested Recursive Polymorphic 19.3 General syntax Summary ©University of Sheffieldcom2010

We have seen built-in data types: primitive data types: Int, Float, Bool, Char, …. composite data types (tuples, lists, strings etc) (Int, String), [Int], String … User-defined data types - these are called algebraic data types Ex: Maybe a Algebraic types: introduced by the keyword data, followed by the name_of_the_type, =, and then the constructor (s). The type name and the constructor(s) must start with upper case letters. Ex: data Pres = Result String | Fail Introduction ©University of Sheffieldcom2010

Consider the example data Pres = Result String | Fail Elements of this type: Fail :: Pres Result “Green”:: Pres Result “m.gheorghe”::Pres This type definition introduces the following constructors Result :: String -> Pres Fail :: Pres Result is like a function but with no equation definition. Result used like a function (!): map Result["a","b"]  [Result "a",Result "b"] Data type construction ©University of Sheffieldcom2010

Every element of Pres is built up from the constructors Result and Fail. This makes it possible to define functions f :: Pres -> X – structural decomposition To define f x, where x :: Pres, deconstruct x into its components, and define f x from these (simpler) components. print’ :: Pres -> String print’ (Result x) = "Result " ++ x -- equation 1 (pattern Result x) print’ Fail = "Fail" -- equation 2 (pattern Fail) When use print’ arg then arg is of type Pres and the result is of type String Structural decomposition ©University of Sheffieldcom2010

Patterns are used for deconstructing elements of an algebraic type. They are basic values: these are all constants of types String, Bool, Char, Int, Float or more complex or algebraic types variables: identifiers starting with lower case letters wildcard _ : this is an anonymous variable for a subexpression as-patterns: they occur in the form Examples: Fail Result “m.gheorghe” Result x Result _ x x) -- like aliases Patterns ©University of Sheffieldcom2010

Patterns may be 1. overlapping - they are evaluated in order. The first pattern that matches is taken: isOK :: Pres -> Bool isOK (Result _) = True -- matched first isOK _ = False -- only when pattern ‘Result _’ fails 2. non-exhaustive - if no pattern matches, then we get a run time error: prop :: Pres -> String prop (Result x) = x --no pattern for constructor ‘Fail’ prop Fail -- does not match ⇒ Program execution error: {prop Pres_Fail} More on Patterns ©University of Sheffieldcom2010

We will become familiar with alternative compound nested recursive polymorphic algebraic data types Algebraic data types - hierarchy ©University of Sheffieldcom2010

In an enumeration type all constructors are constants. Type definition data Temp = Cold | Hot data Season = Spring | Summer | Autumn | Winter Ex: weather :: Season -> Temp weather Summer = Hot weather _ = Cold -- ordering important! Alternatives – Enumeration types ©University of Sheffieldcom2010

In product types there is one constructor with many parameters. Type definition data People = Person String Int Int Ex: aPerson :: People aPerson = Person "M Gheorghe" Like for Pres type, the constructors introduced by an algebraic type definition can be used as functions. Person :: Name -> Office->TelNo->People An alternative definition of type People is given by the type synonym type People =(Name, Office, TelNo) Advantages and limitations of algebraic and synonym types Compound – Product type ©University of Sheffieldcom2010

Type definition data Employees = Employee Name Gender Dates type Name = String data Dates = Date Day Month Year type Day = Int data Month = Jan | Feb | Mar | Apr |May |Jun | Jul | Aug | Sep | Oct | Nov | Dec type Year = Int data Gender = Male | Female Nested algebraic data types ©University of Sheffieldcom2010

inJune :: [Employees]->[Dates] -- returns all male birthday dates in -- June inJune [] = [] inJune (Employee _ Male _ Jun _):es = d:inJune es inJune _:es = inJune es Please note the use of as-pattern Caveat. To show the results obtained add deriving Show to both Dates and Month Question: is it possible to have a nested type with an inner type pointing to the current type? … Nested type - Example ©University of Sheffieldcom2010

Recursive type of simple expressions data Exp = Lit Int| Add Exp Exp| Sub Exp Exp Examples of expressions: 2 Lit Add (Lit 2) (Lit 3) (3-1)+4 Add (Sub (Lit 3) (Lit 1)) (Lit 4) Do you remember any other recursive type? We define functions on type Exp by recursive pattern matching. eval :: Exp->Int –- evaluate expressions eval (Lit n) = n eval (Add e1 e2) = (eval e1) + (eval e2) eval (Sub e1 e2) = (eval e1) – (eval e2) eval e stops for e a finite expression; what if e is an infinite expression? …Yes: Recursive types ©University of Sheffieldcom2010

In Chapter 15 an important (recursive) polymorphic type was introduced, binary searching tree (look at the order of elements). Type definition of a binary searching tree (BSTree) data Tree a = Empty | Leaf a | Node a (Tree a) (Tree a) Specific instances are Tree Int, Tree String, or Tree (Tree Int). A tree of integers: intTree:: Tree Int intTree = Node 5 (Node 2 (Leaf 1) (Node 4 (Leaf 3) Empty)) (Node 8 (Node 6 Empty (Leaf 7)) Empty) Polymorphic types ©University of Sheffieldcom2010

BSTree of Integers ©University of Sheffieldcom

Binary searching tree application: traverse :: Tree a -> [a] -- traverse intTree = -- [1,2,3,4,5,6,7,8] ?? traverse Empty = [] traverse (Leaf x) = [x] traverse (Node x left right) = traverse left ++ [x] ++ traverse right Polymorphic functions on BSTrees (1) ©University of Sheffieldcom2010

Another polymorphic function on binary searching trees removeLast :: Tree a -> (a, Tree a) -- split off last element from a nonempty tree removeLast (Leaf x) = (x,Empty) removeLasT (Node y t_1 Empty)=(y,t_1) removeLast (Node y t_1 t_2) = (x, Node y t_1 t_3) where (x,t_3)=removeLast t_2 Polymorphic functions on BSTrees (2) ©University of Sheffieldcom2010

Remove the last element of a BSTree ©University of Sheffieldcom =(8, )

Other polymorphic functions impose constraints on the type variable a. From Chapter 15 we have: tree_member :: Ord a => a->Tree a -> Bool tree_insert :: Ord a => a->Tree a -> Tree a For searching, the following polymorphic functions are useful: listToTree :: Ord a =>[a] -> Tree a -- turns a list into an ordered search tree listToTree [] = Empty listToTree (x:xs) = tree_insert x (listToTree xs) and treeSort :: Ord a => [a] -> [a] -- sorts a list via ordered tree treeSort xs = traverse(listToTree xs) Polymorphic functions on BSTrees (3) ©University of Sheffieldcom2010

Examples treeSort [2,91,7,35,28] ⇒ [2,7,28,35,91] treeSort['a','r','k',' ','9','i'] ⇒ [‘ ’,’9’,’a’,’i’,’k’,’r’] treeSort[[4,1],[3,9,5],[3],[9,1,0]] ⇒ [[3],[3,9,5],[4,1],[9,1,0]] Sorting using BSTrees ©University of Sheffieldcom2010

The general definition of an algebraic type has the form: data TypeName a_1 a_2 … a_n = ConstructName_1 T_(1,1) T_(1,2)…T_(1,k1) |ConstructName_2 T_(2,1) T_(2,2)…T_(2,k2) … |ConstructName_m T_(m,1) T_(m,2)…T_(m,km) Algebraic data type ©University of Sheffieldcom2010