Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.

Slides:



Advertisements
Similar presentations
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
Advertisements

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 =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Recursive Data Types Koen Lindström Claessen. Modelling Arithmetic Expressions Imagine a program to help school-children learn arithmetic, which presents.
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
Defining new types of data. Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes – enumerated.
Cse536 Functional Programming 1 6/12/2015 Lecture #11, Nov. 01, 2004 Special Guest lecture by Tom Harke Today’s Topics –The Haskell Class system –Instance.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Cse536 Functional Programming 1 6/28/2015 Lecture #3, Oct 4, 2004 Reading Assignments –Finish chapter 2 and begin Reading chapter 3 of the Text Today’s.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
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) Modules.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Chapter 9: Functional Programming in a Typed Language.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Cs7120 (prasad)L7-TDEF1 Type Definitions. cs7120 (prasad)L7-TDEF2 Concrete Types Primitive types ( int, bool, char, string, etc ) Type constructors (
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
Chapter SevenModern Programming Languages1 A Second Look At ML.
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.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
1 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Type declarations.
Polymorphic Functions
Haskell Chapter 7.
String is a synonym for the type [Char].
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Theory of Computation Lecture 4: Programs and Computable Functions II
Haskell Chapter 2.
MPCS 51400: Functional Programming
A lightening tour in 45 minutes
Type Definitions cs776 (prasad) L8tdef.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
PROGRAMMING IN HASKELL
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Review Previously User-defined data types: records, variants
Presentation transcript:

Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee

Lee CSCE 314 TAMU 2  Data Types  Class and Instance Declarations Outline

Lee CSCE 314 TAMU 3 Three constructs for defining types: 1.data - Define a new algebraic data type from scratch, describing its constructors 2.type - Define a synonym for an existing type (like typedef in C) 3.newtype - A restricted form of data that is more efficient when it fits (if the type has exactly one constructor with exactly one field inside it). Uesd for defining “wrapper” types Defining New Types

Lee CSCE 314 TAMU 4 Data Declarations A completely new type can be defined by specifying its values using a data declaration. data Bool = False | True Bool is a new type, with two new values False and True.  The two values False and True are called the constructors for the data type Bool.  Type and constructor names must begin with an upper-case letter.  Data declarations are similar to context free grammars. The former specifies the values of a type, the latter the sentences of a language. More examples from standard Prelude: data () = () -- unit datatype data Char = … | ‘a’ | ‘b’ | …

Lee CSCE 314 TAMU 5 answers :: [Answer] answers = [Yes,No,Unknown] flip :: Answer -> Answer flip Yes = No flip No = Yes flip Unknown = Unknown data Answer = Yes | No | Unknown we can define: Values of new types can be used in the same ways as those of built in types. For example, given

Lee CSCE 314 TAMU 6 next :: Weekday -> Weekday next Mon = Tue next Tue = Wed next Wed = Thu next Thu = Fri next Fri = Sat next Sat = Sun next Sun = Mon workDay :: Weekday -> Bool workDay Sat = False workDay Sun = False workDay _ = True data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun Constructors construct values, or serve as patterns Another example:

Lee CSCE 314 TAMU 7 The constructors in a data declaration can also have parameters. For example, given data Shape = Circle Float | Rect Float Float square :: Float  Shape square n = Rect n n area :: Shape  Float area (Circle r) = pi * r^2 area (Rect x y) = x * y we can define: Constructors with Arguments  Shape has values of the form Circle r where r is a float, and Rect x y where x and y are floats.  Circle and Rect can be viewed as functions that construct values of type Shape: Circle :: Float  Shape Rect :: Float  Float  Shape

Lee CSCE 314 TAMU 8 let x = Person “Jerry” Female 12 y = Person “Tom” Male 12 in … data Person = Person Name Gender Age type Name = String data Gender = Male | Female type Age = Int With just one constructor in a data type, often constructor is named the same as the type (cf. Person). Now we can do: Another example: Quiz: What are the types of the constructors Male and Person? Male :: Gender Person :: Name -> Gender -> Age -> Person

Lee CSCE 314 TAMU 9 name (Person n _ _) = n oldMan (Person _ Male a) | a > 100 = True oldMan (Person _ _ _) = False > let yoda = Person “Yoda” Male 999 in oldMan yoda True findPrsn n m _ _):ps) | n == m = p | otherwise = findPrsn n ps > findPrsn “Tom” [Person “Yoda” Male 999, Person “Tom” Male 7] Person “Tom” Male 7 Pattern Matching

Lee CSCE 314 TAMU 10 Not surprisingly, data declarations themselves can also have parameters. For example, given x = Pair 1 2 y = Pair "Howdy" 42 first :: Pair a b -> a first (Pair x _) = x apply :: (a -> a’)->(b -> b') -> Pair a b -> Pair a' b' apply f g (Pair x y) = Pair (f x) (g y) we can define: Parameterized Data Declarations data Pair a b = Pair a b

Lee CSCE 314 TAMU 11 Another example: Maybe type holds a value (of any type) or holds nothing data Maybe a = Nothing | Just a safediv :: Int  Int  Maybe Int safediv _ 0 = Nothing safediv m n = Just (m `div` n) safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs) we can define: a is a type parameter, can be bound to any type Just True :: Maybe Bool Just “x” :: Maybe [Char] Nothing :: Maybe a

Lee CSCE 314 TAMU 12 Type Declarations A new name for an existing type can be defined using a type declaration. type String = [Char] String is a synonym for the type [Char]. origin :: Pos origin = (0,0) left :: Pos  Pos left (x,y) = (x-1,y) type Pos = (Int,Int) we can define: Type declarations can be used to make other types easier to read. For example, given

Lee CSCE 314 TAMU 13 Like function definitions, type declarations can also have parameters. For example, given type Pair a = (a,a) we can define: mult :: Pair Int -> Int mult (m,n) = m*n copy :: a -> Pair a copy x = (x,x)

Lee CSCE 314 TAMU 14 Type declarations can be nested: type Pos = (Int,Int) type Trans = Pos -> Pos However, they cannot be recursive: type Tree = (Int,[Tree])

Lee CSCE 314 TAMU 15 Recursive Data Types New types can be declared in terms of themselves. That is, data types can be recursive. data Nat = Zero | Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat -> Nat. A value of type Nat is either Zero, or of the form Succ n where n :: Nat. That is, Nat contains the following infinite sequence of values: Example function: Zero Succ Zero Succ (Succ Zero)... add :: Nat -> Nat -> Nat add Zero n = n add (Succ m) n = Succ (add m n)

Lee CSCE 314 TAMU 16 Parameterized Recursive Data Types - Lists data List a = Nil | Cons a (List a) sum :: List Int -> Int sum Nil = 0 sum (Cons x xs) = x + sum xs > sum Nil 0 > sum (Cons 1 (Cons 2 (Cons 2 Nil))) 5

Lee CSCE 314 TAMU 17 Trees A binary Tree is either Tnil, or a Node with a value of type a and two subtrees (of type Tree a) data Tree a = Tnil | Node a (Tree a) (Tree a) Find an element: Compute the depth: depth Tnil = 0 depth (Node _ left right) = 1 + (max (depth left) (depth right)) treeElem :: (a -> Bool) -> Tree a -> Maybe a treeElem p Tnil = Nothing treeElem p v left right) | p v = Just v | otherwise = treeElem p left `combine` treeElem p right where combine (Just v) r = Just v combine Nothing r = r

Lee CSCE 314 TAMU 18 Arithmetic Expressions Consider a simple form of expressions built up from integers using addition and multiplication. 1 +  32

Lee CSCE 314 TAMU 19 Using recursion, a suitable new type to represent such expressions can be declared by: For example, the expression on the previous slide would be represented as follows: data Expr = Val Int | Add Expr Expr | Mul Expr Expr Add (Val 1) (Mul (Val 2) (Val 3))

Lee CSCE 314 TAMU 20 Using recursion, it is now easy to define functions that process expressions. For example: size :: Expr  Int size (Val n) = 1 size (Add x y) = size x + size y size (Mul x y) = size x + size y eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y

Lee CSCE 314 TAMU 21 Note:  The three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr  Many functions on expressions can be defined by replacing the constructors by other functions using a suitable fold function. For example: eval = fold id (+) (*)

Lee CSCE 314 TAMU 22 About Folds A fold operation for Trees: treeFold :: t -> (a -> t -> t -> t) -> Tree a -> t treeFold f g Tnil = f treeFold f g (Node x l r) = g x (treeFold f g l) (treeFold f g r) How? Replace all Tnil constructors with f, all Node constructors with g. Examples: > let tt = Node 1 (Node 2 Tnil Tnil) (Node 3 Tnil (Node 4 Tnil Tnil)) > treeFold 1 (\x y z -> 1 + max y z) tt 4 > treeFold 1 (\x y z -> x * y * z) tt 24 > treeFold 0 (\x y z -> x + y + z) tt 10

Lee CSCE 314 TAMU 23 Experimenting with the above definitions will give you many errors Data types come with no functionality by default, you cannot, e.g., compare for equality, print (show) values etc. Real definition of Bool data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded) A few standard type classes can be listed in a deriving clause Implementations for the necessary functions to make a data type an instance of those classes are generated by the compiler deriving can be considered a shortcut, we will discuss the general mechanism later Deriving

Lee CSCE 314 TAMU 24 Exercises (1) Using recursion and the function add, define a function that multiplies two natural numbers. (2) Define a suitable function fold for expressions, and give a few examples of its use. (3) A binary tree is complete if the two sub-trees of every node are of equal size. Define a function that decides if a binary tree is complete.

Lee CSCE 314 TAMU 25  Data Types  Class and Instance Declarations Outline

Lee CSCE 314 TAMU 26  A new class can be declared using the class construct  Type classes are classes of types, thus not types themselves  Example: class Eq a where (==), (/=) :: a -> a -> Bool -- Minimal complete definition: (==) and (/=) x /= y = not (x == y) x == y = not (x /= y)  For a type a to be an instance of the class Eq, it must support equality and inequality operators of the specified types  Definitions are given in an instance declaration  A class can specify default definitions Type Classes

Lee CSCE 314 TAMU 27 class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y) Let us make Bool be a member of Eq instance Eq Bool where (==) False False = True (==) True True = True (==) _ _ = False  Due to the default definition, (/=) need not be defined  deriving Eq would generate an equivalent definition Instance Declarations

Lee CSCE 314 TAMU 28 class Show a where showsPrec :: Int -> a -> ShowS –- to control parenthesizing show :: a -> String showsPrec _ x s = show x ++ s show x = showsPrec 0 x “” showsPrec can improve efficiency: (((as ++ bs) ++ cs) ++ ds) vs. (as ++). (bs ++). (cs ++). (ds ++) Option 1: data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Show > map show [Mon, Tue, Wed] [“Mon”, “Tue”, “Wed”] Showable Weekdays

Lee CSCE 314 TAMU 29 class Show a where showsPrec :: Int -> a -> ShowS -- to control parenthesizing show :: a -> String showsPrec _ x s = show x ++ s show x = showsPrec 0 x “” Option 2: data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun instance Show Weekday where show Mon = “Monday” show Tue = “Tuesday”... > map show [Mon, Tue, Wed] [“Monday”, “Tuesday”, “Wednesday”] Showable Weekdays

Lee CSCE 314 TAMU 30 Every list is showable if its elements are instance Show a => Show [a] where show [] = “[]” show (x:xs) = “[“ ++ show x ++ showRest xs where showRest [] = “]” showRest (x:xs) = “,” ++ show x ++ showRest xs Now this works: > show [Mon, Tue, Wed] “[Monday,Tuesday,Wednesday]” Parameterized Instance Declarations

Lee CSCE 314 TAMU 31 data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Show, Read, Eq, Ord, Bounded, Enum) *Main> show Wed "Wed” *Main> read "Fri" :: Weekday Fri *Main> Sat Prelude.== Sun False *Main> Sat Prelude.== Sat True *Main> Mon < Tue True *Main> Tue < Tue False *Main> Wed `compare` Thu LT Showable, Readable, and Comparable Weekdays

Lee CSCE 314 TAMU 32 data Weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Show, Read, Eq, Ord, Bounded, Enum) *Main> minBound :: Weekday Mon *Main> maxBound :: Weekday Sun *Main> succ Mon Tue *Main> pred Fri Thu *Main> [Fri.. Sun] [Fri,Sat,Sun] *Main> [minBound.. maxBound] :: [Weekday] [Mon,Tue,Wed,Thu,Fri,Sat,Sun] Bounded and Enumerable Weekdays