Haskell Types, Classes, and Functions, Currying, and Polymorphism

Similar documents
PROGRAMMING IN HASKELL. Chapter 2 - First Steps

CSCE 314 Programming Languages

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

INTRODUCTION TO FUNCTIONAL PROGRAMMING

CS 320: Concepts of Programming Languages

A general introduction to Functional Programming using Haskell

CSCE 314 Programming Languages

Haskell An Introduction

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Standard prelude. Appendix A. A.1 Classes

CSc 372. Comparative Programming Languages. 18 : Haskell Type Classes. Department of Computer Science University of Arizona

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Higher Order Functions

CSC324 Principles of Programming Languages

Informatics 1 Functional Programming Lecture 5. Function properties. Don Sannella University of Edinburgh

Advanced features of Functional Programming (Haskell)

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

CSCE 314 Programming Languages

Lecture 19: Functions, Types and Data Structures in Haskell

Introduction to Programming, Aug-Dec 2006

An introduction introduction to functional functional programming programming using usin Haskell

Shell CSCE 314 TAMU. Functions continued

CSC324 Principles of Programming Languages

Higher Order Functions in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Overloading, Type Classes, and Algebraic Datatypes

Abstract Types, Algebraic Types, and Type Classes

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh

CS 360: Programming Languages Lecture 12: More Haskell

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Haskell Overview II (2A) Young Won Lim 8/9/16

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Programming Languages Fall 2013

INTRODUCTION TO HASKELL

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

Functional Programming Mid-term exam Tuesday 3/10/2017

Haskell Types COMP360

Course year Typeclasses and their instances

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Programming Paradigms

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Haskell Overview II (2A) Young Won Lim 8/23/16

Type-indexed functions in Generic Haskell

Type Processing by Constraint Reasoning

Lecture 2: List algorithms using recursion and list comprehensions

Haskell Overview III (3A) Young Won Lim 10/4/16

Haskell through HUGS THE BASICS

An introduction to functional programming. July 23, 2010

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

A tour of the Haskell Prelude

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Haskell Refresher Informatics 2D

Background Type Classes (1B) Young Won Lim 6/28/18

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

CSc 372 Comparative Programming Languages

Basic types and definitions. Chapter 3 of Thompson

Functional Programming. Overview. Topics. Recall λ-terms. Examples

CS 320: Concepts of Programming Languages

Functional Programming in Haskell Part I : Basics

Exercises on ML. Programming Languages. Chanseok Oh

Structural polymorphism in Generic Haskell

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions

Background Type Classes (1B) Young Won Lim 6/14/18

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Introduction to Functional Programming in Haskell 1 / 56

Haskell Making Our Own Types and Typeclasses

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino

CSCE 314 Programming Languages. Interactive Programming: I/O

User-Defined Algebraic Data Types

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes

CS 457/557: Functional Languages

Advances in Programming Languages

CS 11 Haskell track: lecture 1

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

How does ML deal with +?

Functional Programming for Logicians - Lecture 1

Programming in Haskell Aug-Nov 2015

Programming Language Concepts: Lecture 14

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

Type Systems, Type Inference, and Polymorphism

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

Intro to Haskell Notes: Part 5

Tree Equality: The Problem

CSCE 314 Programming Languages. Functional Parsers

CSCE 314 Programming Languages Functors, Applicatives, and Monads

Lazy Functional Programming in Haskell

Introduction. chapter Functions

Introduction to Haskell

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

SML A F unctional Functional Language Language Lecture 19

Transcription:

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Types, Classes, and Functions, Currying, and Polymorphism

2 Types A type is a collection of related values. For example, Bool contains the two logical values True and False Int contains values 2 29,, 1, 0, 1,, 2 29 1 If evaluating an expression e would produce a value of type t, then e has type T, written e :: T Every well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.

3 Type Errors Applying a function to one or more arguments of the wrong type is called a type error. > 1 + False Error 1 is a number and False is a logical value, but + requires two numbers. Static type checking: all type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time.

Type Annotations Programmer can (and at times must) annotate expressions with type in the form e :: T For example, True :: Bool 5 :: Int -- type is really (Num t) => t (5 + 5) :: Int -- likewise (7 < 8) :: Bool Some expressions can have many types, e.g., 5 :: Int, 5 :: Integer, 5 :: Float GHCi command :type e shows the type of (the result of) e > not False True > :type not False not False :: Bool 4

5 Basic Types Haskell has a number of basic types, including: Bool - logical values Char - single characters String - lists of characters type String = [Char] Int - fixed-precision integers Integer - arbitrary-precision integers Float - single-precision floating-point numbers Double - double-precision floating-point numbers

6 List Types A list is sequence of values of the same type: [False,True,False] :: [Bool] [ a, b, c ] :: [Char] abc :: [Char] [[True, True], []] :: [[Bool]] Note: [t] has the type list with elements of type t The type of a list says nothing about its length The type of the elements is unrestricted Composite types are built from other types using type constructors Lists can be infinite: l = [1..]

7 Tuple Types A tuple is a sequence of values of different types: (False,True) :: (Bool,Bool) (False, a,true) :: (Bool,Char,Bool) ( Howdy,(True,2)) :: ([Char],(Bool,Int)) Note: (t1,t2,,tn) is the type of n-tuples whose i-th component has type ti for any i in 1 n The type of a tuple encodes its size The type of the components is unrestricted Tuples with arity one are not supported: (t) is parsed as t, parentheses are ignored

8 Function Types A function is a mapping from values of one type (T1) to values of another type (T2), with the type T1 -> T2 not :: Bool -> Bool isdigit :: Char -> Bool toupper :: Char -> Char (&&) :: Bool -> Bool -> Bool Note: The argument and result types are unrestricted. Functions with multiple arguments or results are possible using lists or tuples: Only single parameter functions! add :: (Int, Int) Int add (x,y) = x+y zeroto :: Int [Int] zeroto n = [0..n]

9 Curried Functions Functions with multiple arguments are also possible by returning functions as results: add :: (Int,Int) Int add (x,y) = x+y add :: Int (Int Int) add x y = x+y add takes an int x and returns a function add x. In turn, this function takes an int y and returns the result x+y. Note: add and add produce the same final result, but add takes its two arguments at the same time, whereas add takes them one at a time Functions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions.

Functions with more than two arguments can be curried by returning nested functions: mult :: Int (Int (Int Int)) mult x y w = x*y*w mult takes an integer x and returns a function mult x, which in turn takes an integer y and returns a function mult x y, which finally takes an integer w and returns the result x*y*w Note: Functions returning functions: our first example of higher-order functions Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form 10

11 Why is Currying Useful? Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function. For example: add 1 :: Int -> Int take 5 :: [a] -> [a] drop 5 :: [a] -> [a] map :: (a->b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs > map (add 1) [1,2,3] [2,3,4]

12 Currying Conventions To avoid excess parentheses when using curried functions, two simple conventions are adopted: 1. The arrow (type constructor) associates to the right. Int Int Int Int Means Int (Int (Int Int)) 1. As a consequence, it is then natural for function application to associate to the left. mult x y z Means ((mult x) y) z

13 Polymorphic Functions A function is called polymorphic ( of many forms ) if its type contains one or more type variables. Thus, polymorphic functions work with many types of arguments. length :: [a] Int for any type a, length takes a list of values of type a and returns an integer a is a type variable id :: a a for any type a, id maps a value of type a to itself head :: [a] a take :: Int [a] [a]

Polymorphic Types CSCE 314 TAMU Fall 2017 Type variables can be instantiated to different types in different circumstances: > length [False,True] 2 > length [1,2,3,4] 4 a = Bool a = Int Type variables must begin with a lower-case letter, and are usually named a, b, c, etc. 14

15 More on Polymorphic Types What does the following function do, and what is its type? twice :: (t -> t) -> t -> t twice f x = f (f x) > twice tail abcd cd What is the type of twice twice? The parameter and return type of twice are the same (t -> t) Thus, twice and twice twice have the same type So, twice twice :: (t -> t) -> t -> t

Overloaded Functions A polymorphic function is called overloaded if its type contains one or more class constraints. CSCE 314 TAMU Fall 2017 sum :: Num a [a] a for any numeric type a, sum takes a list of values of type a and returns a value of type a Constrained type variables can be instantiated to any types that satisfy the constraints: > sum [1,2,3] 6 a = Int > sum [1.1,2.2,3.3] a = Float 6.6 > sum [ a, b, c ] Char is not a numeric type ERROR 16

17 Class Constraints Recall that polymorphic types can be instantiated with all types, e.g., id :: t -> t length :: [t] -> Int This is when no operation is subjected to values of type t What are the types of these functions? min :: Ord a => a -> a -> a min x y = if x < y then x else y elem :: Eq a => a -> [a] -> Bool elem x (y:ys) x == y = True elem x (y:ys) = elem x ys elem x [] = False

Class Constraints Recall that polymorphic types can be instantiated with all types, e.g., id :: t -> t length :: [t] -> Int This is when no operation is subjected to values of type t What are the types of these functions? min :: Ord a => a -> a -> a min x y = if x < y then x else y elem :: Eq a => a -> [a] -> Bool elem x (y:ys) x == y = True elem x (y:ys) = elem x ys elem x [] = False Ord a and Eq a are class constraints Type variables can only be bound to types that satisfy the constraints 18

19 Type Classes CSCE 314 TAMU Fall 2017 Constraints arise because values of the generic types are subjected to operations that are not defined for all types: min :: Ord a => a -> a -> a min x y = if x < y then x else y elem :: Eq a => a -> [a] -> Bool elem x (y:ys) x == y = True elem x (y:ys) = elem x ys elem x [] = False Ord and Eq are type classes: Num (Numeric types) Eq (Equality types) Ord (Ordered types) (+) :: Num a a a a (==) :: Eq a a a Bool (<) :: Ord a a a Bool

20 CSCE 314 TAMU Fall 2017 Haskell 98 Class Hierarchy -- For detailed explanation, refer to http://www.haskell.org/onlinereport/basic.html

21 The Eq and Ord Classes class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a compare x y x == y = EQ x <= y = LT otherwise = GT CSCE 314 TAMU Fall 2017 x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y x <= y = y otherwise = x min x y x <= y = x otherwise = y

22 The Eq and Ord Classes class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a compare x y x == y = EQ x <= y = LT otherwise = GT CSCE 314 TAMU Fall 2017 x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y x <= y = y otherwise = x min x y x <= y = x otherwise = y

23 The Show and Read Classes class Show a where show :: a -> String class Read a where read :: String -> a Many types are showable and/or readable. > show 10 > read 10 :: Int 10 10 > show [1,2,3] > read ( [1,2,3] ) :: [Int] [1,2,3] [1,2,3] [1,2] ) > map (* 2.0) (read [2.0,4.0]

24 Hints and Tips When defining a new function in Haskell, it is useful to begin by writing down its type. Within a script, it is good practice to state the type of every new function defined. When stating the types of polymorphic functions that use numbers, equality or orderings, take care to include the necessary class constraints.

25 Exercises (1) What are the types of the following values? [ a, b, c ] ( a, b, c ) [(False, 0 ),(True, 1 )] ([False,True],[ 0, 1 ]) [tail,init,reverse]

26 (2) What are the types of the following functions? second xs swap (x,y) pair x y = head (tail xs) = (y,x) = (x,y) double x = x*2 palindrome xs = reverse xs == xs lessthanhalf x y = x * 2 < y (3) Check your answers using GHCi.

27 second :: [a] -> a second xs = head (tail xs) swap :: (a, b) -> (b, a) swap (x,y) = (y,x) pair :: a -> b -> (a, b) pair x y = (x,y) double :: Num a => a -> a double x = x*2 palindrome :: Eq a => [a] -> Bool palindrome xs = reverse xs == xs lessthanhalf :: (Num a, Ord a) => a -> a -> Bool lessthanhalf x y = x * 2 < y

28 second :: [a] -> a second xs = head (tail xs) swap :: (a, b) -> (b, a) swap (x,y) = (y,x) pair :: a -> b -> (a, b) pair x y = (x,y) double :: Num a => a -> a double x = x*2 palindrome :: Eq a => [a] -> Bool palindrome xs = reverse xs == xs lessthanhalf :: (Num a, Ord a) => a -> a -> Bool lessthanhalf x y = x * 2 < y

29 The Eq and Ord Classes class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a compare x y x == y = EQ x <= y = LT otherwise = GT CSCE 314 TAMU Fall 2017 x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y x <= y = y otherwise = x min x y x <= y = x otherwise = y

30 The Enum Class CSCE 314 TAMU Fall 2017 class Enum a where toenum fromenum :: Int -> a :: a -> Int succ, pred :: a -> a... -- Minimal complete definition: toenum, fromenum Note: these methods only make sense for types that map injectively into Int using fromenum and toenum. succ = toenum. (+1). fromenum pred = toenum. (subtract 1). fromenum