Course year Typeclasses and their instances
|
|
- Naomi Wright
- 5 years ago
- Views:
Transcription
1 Course year Typeclasses and their instances Doaitse Swierstra and Atze Dijkstra with extra s Utrecht University September 29, 2016
2 1. The basics 2
3 Overloading versus parametric polymorphism 1 Many functions can be applied to values of different types. 3
4 Overloading versus parametric polymorphism 1 Many functions can be applied to values of different types. There are two underlying principles: A parametrically polymorphic function works on some specific data structure, without making explicit use of properties of the elements contained. Examples are length, concat, (.) and map. 3
5 Overloading versus parametric polymorphism 1 Many functions can be applied to values of different types. There are two underlying principles: A parametrically polymorphic function works on some specific data structure, without making explicit use of properties of the elements contained. Examples are length, concat, (.) and map. An overloaded function also works on different types, but then the implementations differ; they only share the name. Examples are +, for which one version adds Ints and another Floats. The operator <= has versions for Int, Float, Char, tuples and lists. 3
6 Why type classes? (1) 1 What problem are we solving? Consider sort :: [Int] > [Int] sort = foldr insert [ ] insert x [ ] = [x] insert x xs@(y : ys) x <= y = x : xs true = y : insert x ys 4
7 Why type classes? (1) 1 What problem are we solving? Consider sort :: [Int] > [Int] sort = foldr insert [ ] insert x [ ] = [x] insert x xs@(y : ys) x <= y = x : xs true = y : insert x ys We can also pass the comparison function, that compares values of the right type, a: sort :: (a > a > Bool) > [a] > [a] sort lte = foldr (insert lte) [ ] insert lte x xs@(y : ys) x lte y = x : xs true = y : insert lte x ys 4
8 Why type classes? (2) 1 Recall sort :: (a > a > Bool) > [a] > [a] sort lte = foldr (insert lt) [ ] insert lte x xs@(y : ys) x lte y = x : xs true = y : insert x ys Wouldn t it be nice not to have to pass around lte all the time? And to decide which lte to use, based on the actual type of the values passed to sort? 5
9 Why type classes? (2) 1 Recall sort :: (a > a > Bool) > [a] > [a] sort lte = foldr (insert lt) [ ] insert lte x xs@(y : ys) x lte y = x : xs true = y : insert x ys Wouldn t it be nice not to have to pass around lte all the time? And to decide which lte to use, based on the actual type of the values passed to sort? Indeed it can: by means of type classes we can state for every comparable type how it should be compared. Then the compiler can figure out which comparison function to use. 5
10 Classes 1 A class definition specifies a coherent collection of overloaded function names with their types. Instances of a class provide the specific function definitions (for a given type). The types Int and Float are instances of the class Num. 6
11 Classes 1 A class definition specifies a coherent collection of overloaded function names with their types. Instances of a class provide the specific function definitions (for a given type). The types Int and Float are instances of the class Num. The operator (+) is defined for each type that is an instance of the class Num. 6
12 Classes 1 A class definition specifies a coherent collection of overloaded function names with their types. Instances of a class provide the specific function definitions (for a given type). The types Int and Float are instances of the class Num. The operator (+) is defined for each type that is an instance of the class Num.This fact is expressed by the type of the operator +: (+) :: Num a => a > a > a 6
13 Classes 1 A class definition specifies a coherent collection of overloaded function names with their types. Instances of a class provide the specific function definitions (for a given type). The types Int and Float are instances of the class Num. The operator (+) is defined for each type that is an instance of the class Num.This fact is expressed by the type of the operator +: (+) :: Num a => a > a > a One can read this as: + has type a > a > a provided there is proof that a in an instance of Num. 6
14 Classes 1 A class definition specifies a coherent collection of overloaded function names with their types. Instances of a class provide the specific function definitions (for a given type). The types Int and Float are instances of the class Num. The operator (+) is defined for each type that is an instance of the class Num.This fact is expressed by the type of the operator +: (+) :: Num a => a > a > a One can read this as: + has type a > a > a provided there is proof that a in an instance of Num. 6 One can think of Num a => as an extra implicit argument, containing the actual definition of the specific (+).
15 A different outlook 1 Type classes may remind you of a record, or an interface or abstract class from the OO world Instances correspond at run-time to so called dictionaries They contain concrete implementations of functions (and constants) listed in the type class When we use such functions, the compiler can find the dictionary to use based on the actual types If you add Ints you use a different dictionary then if you add Floats Since the type decides the dictionary, you can have only one implementation per type (can you, really?) 7
16 Class and instance declarations 1 Besides the standard classes (such as Num, Eq and Ord) you can define your own classes This is a very powerful technique to parametrize your code without too much effort Many Haskell libraries depend extensively on these concepts It does make programs harder to debug: you see a function call overloadedfun of which many instances exist. If it generates an exception, which instance is to blame? 8
17 The first version of the class Num 1 A simple variant of the class Num from the Prelude is: class Num a where (+), ( ), ( ), (/) :: a > a > a negate :: a > a 9
18 class declarations 1 A class declaration consists of the following elements: the keyword class; the name of the class (Num in our case); a type-variable (a in our case); the keyword where; type declarations for operators en functions, in which the type parameter of the class may occur. The functions can be polymorphic. 10
19 The instance Num Int 1 In an instance declaration we provide definitions for the functions and operators of the class for a specific type: 11
20 The instance Num Int 1 In an instance declaration we provide definitions for the functions and operators of the class for a specific type: instance Num Int where (+) = primplusint ( ) = primminusint ( ) = primmulint (/) = primdivint negate = primnegint 11
21 Instance declarations 1 An instance declaration contains the following parts: the keyword instance; the name of a declared class (Num); the type for which we are declaring an instance (Int); the keyword where; definitions for the functions and operators of the class for this specific type 12
22 Num Float 1 instance Num Float where (+) = primplusfloat ( ) = primminusfloat ( ) = primmulfloat (/) = primdivfloat negate = primnegfloat 13
23 Defining new instances 1 We can make the rational numbers an instance of Num too: data Rational = Rat (Int, Int) instance Num Rational where Rat (x, y) + Rat (p, q) = simplify (Rat (x q + y p, y q)) Rat (x, y) Rat (p, q) = simplify (Rat (x q y p, y q)) Rat (x, y) Rat (p, q) = simplify (Rat (x p, y q)) Rat (x, y) / Rat (p, q) = simplify (Rat (x q, y p)) negate (Rat (x, y)) = Rat (negate x, y) simplify (Rat (x, y)) = Rat (x div f, y div f ) where f = gcd x y 14
24 Defining a new type class 1 (Taken from Learn You A Haskell For Great Good!) JavaScript (and many other languages) allows you to write anything inside a condition Each type has special rules on how to interpret them as booleans We shall use type classes to attain the same thing here 15
25 A class for coercion 1 class YesNo a where yesno :: a > Bool Essentially, an instance of yesno tells us for a value of that instance whether it coerces to True or to False 16
26 What about instances 1 instance YesNo Bool where yesno = id instance YesNo Int where yesno 0 = False yesno = True instance YesNo [a] where yesno [ ] = False yesno = True And on and on... Note that the list case does not depend on having a YesNo instance for a 17
27 Example uses 1? yesno (length []) False? yesno "bleep" True? yesno "" False? yesno True True? yesno [] False? yesno [0,0,0] True 18
28 Dynamic languages are hard to model 1? yesno "0" True? yesno "a" True? yesno [0] True Can we have that 0 is also False, but keep the others True? That is a bit harder, since we then want to give [Char] other rules than other [a]. Allowing overlapping might just work Modelling different languages is even harder, since they do not correspond on these special cases 19
29 2. Back to the standard classes 20
30 Eq 2 The Prelude contains the definition of Eq: class Eq a where (==), (/ =) :: a > a > Bool 21
31 and definitions for all the standard types 2 22 instance Eq Int where x == y = primeqint x y x/ = y = not (x == y) instance Eq Float where x == y = primeqfloat x y x/ = y = not (x == y) instance Eq Char where x == y = ord x == ord y x/ = y = not (x == y) instance Eq Bool where True == True = True False == False = True True == False = False False == True = False x/ = y = not (x == y)
32 Eq revisited 2 class Eq a where (==), (/ =) :: a > a > Bool x/ = y = not (x == y) x == y = not (x/ = y) If we define an instance and omit either == or / =, then the default definition is taken. 23
33 Eq revisited 2 class Eq a where (==), (/ =) :: a > a > Bool x/ = y = not (x == y) x == y = not (x/ = y) If we define an instance and omit either == or / =, then the default definition is taken. Do not forget to provide at least one! 23
34 Using Eq instances in defining new instances 2 We can make Rational an instance of Eq instance Eq Rational where Rat (x, y) == Rat (p, q) = x q == y p 24
35 Using Eq instances in defining new instances 2 We can make Rational an instance of Eq instance Eq Rational where Rat (x, y) == Rat (p, q) = x q == y p The == in the left hand side of the definition refers to equality for Rationals which is being defined here, whereas the == in the right hand side refers to equality for Int s. 24
36 Super classes 2 In the class definition of Ord we can require that the types which will be instances of Ord have to be instances of Eq too: class Eq a => Ord a where (<=), (<), (>=), (>) :: a > a > Bool max, min :: a > a > a All functions except <= have default definitions, expressed in terms of <= and ==. 25
37 The class Num 2 Num also requires its instances to be instance of Eq: class Eq a => Num a where (+), ( ), ( ), (/) :: a > a > a negate :: a > a There is no semantic reason for this; it is a way of expressing the intentions of the library designers. 26
38 Parameterised instances 2 By giving a single definition we can make all lists an instance of Eq: instance Eq a => Eq [a] where [ ] == [ ] = True [ ] == (y : ys) = False (x : xs) == [ ] = False (x : xs) == (y : ys) = x == y && xs == ys We have a single definition covering an infinite number of instances. 27
39 Parameterised instances 2 By giving a single definition we can make all lists an instance of Eq: instance Eq a => Eq [a] where [ ] == [ ] = True [ ] == (y : ys) = False (x : xs) == [ ] = False (x : xs) == (y : ys) = x == y && xs == ys We have a single definition covering an infinite number of instances. One may read the first line as: if a is an instance of Eq, then [a] is also an instance of Eq. Note that this applies repeatedly as well, e.g., [[[Int]]] 27
40 Parameterised instances 2 By giving a single definition we can make all lists an instance of Eq: instance Eq a => Eq [a] where [ ] == [ ] = True [ ] == (y : ys) = False (x : xs) == [ ] = False (x : xs) == (y : ys) = x == y && xs == ys We have a single definition covering an infinite number of instances. x == y compares two elements (Eq a proves that we can do this) xs == ys is a recursive call to the function being defined 27
41 Another example 2 The Prelude defines a lexicographic ordering between lists: instance Ord a => Ord [a] where [ ] <= ys = True (x : xs) <= [ ] = False (x : xs) <= (y : ys) = x < y (x == y && xs <= ys) 28
42 More than one instance parameter 2 Instances can specify several preconditions (parameters). We use it to define equality for tuples: instance (Eq a, Eq b) => Eq (a, b) where (x, y) == (u, v) = x == u && y == v Elements of type (a, b) can be compared provided a and b can be compared, i.e. are instances of Eq. 29
43 Attention! 2 The reserved symbol => can be used in types, in instance-declarations and in class-declarations: f :: Num a => a > a is a type-declaration: f is a function with type a > a provided a is a type in the class Num 30
44 Attention! 2 The reserved symbol => can be used in types, in instance-declarations and in class-declarations: f :: Num a => a > a is a type-declaration: f is a function with type a > a provided a is a type in the class Num instance Eq a => Eq [a] is an instance-declaration: [a] is an instance of Eq provided a is 30
45 Attention! 2 The reserved symbol => can be used in types, in instance-declarations and in class-declarations: f :: Num a => a > a is a type-declaration: f is a function with type a > a provided a is a type in the class Num instance Eq a => Eq [a] is an instance-declaration: [a] is an instance of Eq provided a is class Eq a => Ord a is a class-declaration: all instances of the new class Ord have to be an instance of Eq too 30
46 Attention! 2 The reserved symbol => can be used in types, in instance-declarations and in class-declarations: f :: Num a => a > a is a type-declaration: f is a function with type a > a provided a is a type in the class Num instance Eq a => Eq [a] is an instance-declaration: [a] is an instance of Eq provided a is class Eq a => Ord a is a class-declaration: all instances of the new class Ord have to be an instance of Eq too The common theme is that before the => you write an assumption, or pre-condition 30
47 3. More standard classes 31
48 Standard classes 3 The prelude defines the following classes: Eq, the class of type which can be compared for equality; Ord, the class of types which have an ordering relation; Num, the class of types with have numeric properties; Enum, the class of types which can be enumerated; Ix, the class of types which can be used as an array index; Read and Show, the classes of types which have an external representation. 32
49 Show 3 Types which have external (i.e. String representations) are instances of Show show :: Show a => a > String 33
50 Show 3 Types which have external (i.e. String representations) are instances of Show show :: Show a => a > String All elementary types and composed types, such as lists and tuples, are instance of Show. 33
51 Show 3 Types which have external (i.e. String representations) are instances of Show show :: Show a => a > String All elementary types and composed types, such as lists and tuples, are instance of Show. Having show helps the interpreter decide how to display answers to you. So make sure you make every datatype an instance of Show! 33
52 All those instances: use deriving 3 Implementing show for every datatype bores quickly. You can let Haskell derive show (and other instances besides) when you define a new datatype: data Person = APerson String String Int deriving (Eq, Show, Read) generates sensible defaults for comparing, printing and reading Person values. If they are not what you want, do not derive them but write your own instances. 34
53 Enum 3 Enum is defined as: class Ord a => Enum a where enumfrom :: a > [a] enumfromthen :: a > a > [a] enumfromto :: a > a > [a] enumfromthento :: a > a > a > [a] 35
54 Use of Enum 3 Example uses: enumfrom 4 = [4, 5, 6, 7, 8,... enumfromthen 4 6 = [4, 6, 8,... enumfromto c f = [ c, d, e, f ] enumfromthento = [1.0, 1.5, 2.0, 2.5, 3.0] 36
55 Use of Enum 3 Example uses: enumfrom 4 = [4, 5, 6, 7, 8,... enumfromthen 4 6 = [4, 6, 8,... enumfromto c f = [ c, d, e, f ] enumfromthento = [1.0, 1.5, 2.0, 2.5, 3.0] The functions are used to desugar the list notations [x..], [x, y..], [x.. y] and [x, y.. z] 36
56 Enum Int 3 instance Enum Int where enumfrom i = iterate (1+) i enumfromthen i j = iterate ((j i)+) i 37
57 Default definitions for enumfromto and enumfromthento 3 class Ord a => Enum a where... enumfromto i j = takewhile (j >=) (enumfrom i) enumfromthento i i j i > i = takewhile (j >=) (enumfromthen i i ) otherwise = takewhile (j <=) (enumfromthen i i ) 38
58 Default definitions for enumfromto and enumfromthento 3 class Ord a => Enum a where... enumfromto i j = takewhile (j >=) (enumfrom i) enumfromthento i i j i > i = takewhile (j >=) (enumfromthen i i ) otherwise = takewhile (j <=) (enumfromthen i i ) This explains why instances of Enum have to be instances of Ord too. 38
59 The class Functor 3 The function map :: (a > b) > [a] > [b] is generalised in the Prelude to: class Functor f where fmap :: (a > b) > f a > f b This captures the pattern that values of type f a somehow contain values of type a, which can be converted to values of type b. 39
60 4. Overloaded numeric constants 40
61 How Haskell deals with constants 4 The class mechanism allows different versions of (+) to co-exist. 41
62 How Haskell deals with constants 4 The class mechanism allows different versions of (+) to co-exist. Thus far constants cannot co-exist, and we have to write: Int: 3 Float: 3.0 Rational: Rat (3, 1) Complex: Comp (3.0, 0.0) 41
63 A slight snag 4 If we define half = Rat (1, 2), we cannot write: 3 half because half has type Rational, whereas 3 has type Int. 42
64 Num revisited 4 To solve this problem the class Num contains one more function: frominteger. class Num a where (+), ( ), ( ), (/) :: a > a > a negate :: a > a frominteger :: Integer > a 43
65 Num revisited 4 To solve this problem the class Num contains one more function: frominteger. class Num a where (+), ( ), ( ), (/) :: a > a > a negate :: a > a frominteger :: Integer > a For each instance of Num we thus have to specify how an Integer value can be converted to an a value. Integer is the type of infinite precision integers, Int the type of finite precision integers. 43
66 For our own instances of Num... 4 we define our own specific conversion function: instance Num Rational where... frominteger n = Rat (frominteger n, 1) 44
67 For our own instances of Num... 4 we define our own specific conversion function: instance Num Rational where... frominteger n = Rat (frominteger n, 1) This means the symbol 3 is considered to be of type 3 :: Num a => a leaving the choice open until the context tells us what a should be. If a Rational is needed, frominteger converts it to the right rational. 44
68 5. Problems with type classes 45
69 Problem 1: Cannot derive instance 5 You get this error message when you need (implicitly) an instance for a type but you did not declare one:? (1,2,3) == (4,5,6) ERROR: Cannot derive instance in expression *** Expression : (1,2,3) == (4,5,6) *** Required instance : Eq (Int,Int,Int) 46
70 Problem 1: Cannot derive instance 5 You get this error message when you need (implicitly) an instance for a type but you did not declare one:? (1,2,3) == (4,5,6) ERROR: Cannot derive instance in expression *** Expression : (1,2,3) == (4,5,6) *** Required instance : Eq (Int,Int,Int) Here the standard prelude does not contain an instance declaration of Eq for triples. GHC is more permissive however. 46
71 Problem 1: Cannot derive instance 5 You get this error message when you need (implicitly) an instance for a type but you did not declare one:? (1,2,3) == (4,5,6) ERROR: Cannot derive instance in expression *** Expression : (1,2,3) == (4,5,6) *** Required instance : Eq (Int,Int,Int) Here the standard prelude does not contain an instance declaration of Eq for triples. GHC is more permissive however. The solution lies in adding the missing instance declaration. 46
72 ... continued... 5 You also get this error message if you try to compare functions, since function types are not instances of Eq:? tail == drop 1 ERROR: Cannot derive instance in expression *** Expression : tail == drop 1 *** Required instance : Eq ([a]->[a]) But here you do not expect to be able to provide a sensible instance, but instead you may want to pass a value to each of the functions and compare the results: \ xs > tail xs == drop 1 xs 47
73 Problem 2: overlapping instances 5 Another problem arises if an instance declaration is a special case of a more general case. 48
74 Problem 2: overlapping instances 5 Another problem arises if an instance declaration is a special case of a more general case. The Prelude defines tuples as an instance of Eq: instance (Eq a, Eq b) => Eq (a, b) where (x, y) == (u, v) = x == u && y == v 48
75 Problem 2: overlapping instances 5 Another problem arises if an instance declaration is a special case of a more general case. The Prelude defines tuples as an instance of Eq: instance (Eq a, Eq b) => Eq (a, b) where (x, y) == (u, v) = x == u && y == v We now try define rational numbers as a tuple, and provide an instance for this case: type Rational = (Int, Int) instance Eq Rational where (x, y) == (u, v) = x v == u y 48
76 ... continued... 5 For (1, 2) == (2, 4) it is now no longer possible to decide which definition for == to take. 49
77 ... continued... 5 For (1, 2) == (2, 4) it is now no longer possible to decide which definition for == to take. Hence the compiler reports: ERROR "file" (line 12): Overlapping instances for class "Eq" *** This instance : Eq (Int,Int) *** Overlaps with : Eq (a,a) *** Common instance : Eq (Int,Int) 49
78 ... continued... 5 For (1, 2) == (2, 4) it is now no longer possible to decide which definition for == to take. Hence the compiler reports: ERROR "file" (line 12): Overlapping instances for class "Eq" *** This instance : Eq (Int,Int) *** Overlaps with : Eq (a,a) *** Common instance : Eq (Int,Int) This problem can be solved here by defining: data Rational = Rat (Int, Int) 49
79 Problem 3: Unresolved overloading 5 Sometimes the compiler has insufficient information available to decide which instance to take:? frominteger 1 + frominteger 2 ERROR: Unresolved overloading *** type : Num a => a 50
80 Problem 3: Unresolved overloading 5 Sometimes the compiler has insufficient information available to decide which instance to take:? frominteger 1 + frominteger 2 ERROR: Unresolved overloading *** type : Num a => a For frominteger we can take the Int version or the Float version (or another). 50
81 Problem 3: Unresolved overloading 5 Sometimes the compiler has insufficient information available to decide which instance to take:? frominteger 1 + frominteger 2 ERROR: Unresolved overloading *** type : Num a => a For frominteger we can take the Int version or the Float version (or another). Since this is confusing the system will default to Int in such cases. 50
82 How to repair 5 Usually such problems can be solved by providing a type annotation:? (frominteger 1 + frominteger 2) :: Int 3 51
83 Problem 4: Ambiguity 5 show :: Show a => a > String read :: Read a => String > a f x = show (read x) No instance for (Show a0) arising from a use of show The type variable a0 is ambiguous Possible fix: add a type signature that fixes these type variable(s) No instance for (Read a0) arising from a use of read The type variable a0 is ambiguous Possible fix: add a type signature that fixes these type variable(s) 52 What is the (intermediate) type of read x that is passed to show?
CS 320: Concepts of Programming Languages
CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 08: Type Classes o o Review: What is a type class? Basic Type Classes: Eq, Ord, Enum, Integral,
More informationAbstract Types, Algebraic Types, and Type Classes
Informatics 1 Functional Programming Lectures 13 and 14 Monday 9 and Tuesday 10 November 2009 Abstract Types, Algebraic Types, and Type Classes Philip Wadler University of Edinburgh Reminders Tutorial
More informationUser-Defined Algebraic Data Types
72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces
More informationInformatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh
Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November 2013 Type Classes Don Sannella University of Edinburgh Mock exam Slots and rooms have now been assigned Mon 18
More informationCS 457/557: Functional Languages
CS 457/557: Functional Languages From Trees to Type Classes Mark P Jones Portland State University 1 Trees:! " There are many kinds of tree data structure.! " For example: data BinTree a = Leaf a BinTree
More informationCSc 372. Comparative Programming Languages. 18 : Haskell Type Classes. Department of Computer Science University of Arizona
1/20 CSc 372 Comparative Programming Languages 18 : Haskell Type Classes Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg 2/20 Type Classes Type
More informationOverloading, Type Classes, and Algebraic Datatypes
Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827
More informationPROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions
PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}
More informationHaskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2)
Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes Henrik Nilsson University of Nottingham, UK What is the type of (==)? E.g. the following both work: 1 == 2 a == b I.e., (==) can be used to compare
More informationCSci 450: Org. of Programming Languages Overloading and Type Classes
CSci 450: Org. of Programming Languages Overloading and Type Classes H. Conrad Cunningham 27 October 2017 (after class) Contents 9 Overloading and Type Classes 1 9.1 Chapter Introduction.........................
More informationProgramming Paradigms
PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE
More informationProgramming Languages 3. Definition and Proof by Induction
Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.
More informationAdvances in Programming Languages
T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U
More informationAdvanced features of Functional Programming (Haskell)
Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of
More informationHaskell Types, Classes, and Functions, Currying, and Polymorphism
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
More informationFunctional Programming in Haskell Part I : Basics
Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian
More informationIntroduction to Programming, Aug-Dec 2006
Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components
More informationFUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino
1 FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS Tatsuya Hagino hagino@sfc.keio.ac.jp 2 Static Type Checking and Type Inference Type a set of values Bool = { True, False } Char = { 'a', 'b',... } Int = {...
More informationINTRODUCTION TO HASKELL
INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be
More informationSolution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors
Solution sheet 1 Introduction Please note that there can be other solutions than those listed in this document. This is a literate Haskell file which is available as PDF, as well as literate Haskell source
More informationCS 360: Programming Languages Lecture 12: More Haskell
CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due
More information(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.
EXAM FUNCTIONAL PROGRAMMING Tuesday the 1st of October 2016, 08.30 h. - 10.30 h. Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain
More informationLecture 2: List algorithms using recursion and list comprehensions
Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns
More informationIntroduction to Programming: Lecture 10
Introduction to Programming: Lecture 10 K Narayan Kumar Chennai Mathematical Institute http://www.cmi.ac.in/~kumar 10 Sep 2012 Organizing functions as Modules Organize functions into modules. Organizing
More informationType Classes in Haskell Tom Schrijvers. Leuven Haskell User Group
Type Classes in Haskell Tom Schrijvers Leuven Haskell User Group Haskell Research Team Partners Monads Type Classes GHC Folds Pattern Matching Equational Reasoning DSLs Advanced Types Adhoc Overloading
More informationStandard prelude. Appendix A. A.1 Classes
Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from
More informationA tour of the Haskell Prelude
A tour of the Haskell Prelude Bernie Pope 2001 1 Haskell The Haskell language was conceived during a meeting held at the 1987 Functional Programming and Computer Architecture conference (FPCA 87). At the
More informationBackground Type Classes (1B) Young Won Lim 6/28/18
Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2
More informationLecture 4: Higher Order Functions
Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function
More informationCSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona
1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists
More informationBackground Type Classes (1B) Young Won Lim 6/14/18
Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2
More informationOverview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping
Overview Declarative Languages D7012E Lecture 4: The Haskell type system Fredrik Bengtsson / Johan Nordlander Overloading & polymorphism Type classes instances of type classes derived type classes Type
More informationHaskell Overview III (3A) Young Won Lim 10/4/16
(3A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published
More informationData Types. Every program uses data, either explicitly or implicitly to arrive at a result.
Every program uses data, either explicitly or implicitly to arrive at a result. Data in a program is collected into data structures, and is manipulated by algorithms. Algorithms + Data Structures = Programs
More informationThe List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona
The List Datatype CSc 372 Comparative Programming Languages 6 : Haskell Lists Department of Computer Science University of Arizona collberg@gmail.com All functional programming languages have the ConsList
More informationCS 320: Concepts of Programming Languages
CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard
More informationProgramming Languages Fall 2013
Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy
More informationPractical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.
Practical Practical An introduction to functional programming July 21, 2011 Contents Practical Practical is fun, and that s what it s all about! Even if seems strange to you at first, don t give up. Learning
More informationCSc 372 Comparative Programming Languages
CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg
More informationPolymorphism Overview (1A) Young Won Lim 2/20/18
Polymorphism Overview (1A) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2
More informationProgramming with Math and Logic
.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing
More informationCSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions
1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions
More informationIntroduction to Haskell
Introduction to Haskell Matt Mullins Texas A&M Computing Society October 6, 2009 Matt Mullins (TACS) Introduction to Haskell October 6, 2009 1 / 39 Outline Introduction to Haskell Functional Programming
More informationINTRODUCTION TO FUNCTIONAL PROGRAMMING
INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,
More informationHow does ML deal with +?
How does ML deal with +? Moscow ML version 2.00 (June 2000) - op +; > val it = fn : int * int -> int - 1 + 1; > val it = 2 : int - 1.0 + 1.0; > val it = 2.0 : real - false + false;! Overloaded + cannot
More informationShell CSCE 314 TAMU. Higher Order Functions
1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.
More informationHomework 1: Functional Programming, Haskell
Com S 541 Programming Languages 1 September 25, 2005 Homework 1: Functional Programming, Haskell Due: problems 1 and 3, Thursday, September 1, 2005; problems 4-9, Thursday, September 15, 2005; remaining
More informationHaskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza
Haskell 101 (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell
More informationn n Try tutorial on front page to get started! n spring13/ n Stack Overflow!
Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!
More informationType system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)
Type system EDAN40: Functional Programming Types and Type Classes (revisited) Jacek Malec Dept. of Computer Science, Lund University, Sweden April 3rd, 2017 In programming languages, a type system is a
More informationTopic 6: Partial Application, Function Composition and Type Classes
Topic 6: Partial Application, Function Composition and Type Classes Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,
More informationTopic 6: Partial Application, Function Composition and Type Classes
Topic 6: Partial Application, Function Composition and Type Classes 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,
More informationCSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.
CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:
More informationCS 320 Midterm Exam. Fall 2018
Name: BU ID: CS 320 Midterm Exam Fall 2018 Write here the number of the problem you are skipping: You must complete 5 of the 6 problems on this exam for full credit. Each problem is of equal weight. Please
More informationA general introduction to Functional Programming using Haskell
A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And
More informationHaskell Types COMP360
Haskell Types COMP360 No computer has ever been designed that is ever aware of what it's doing; but most of the time, we aren't either. Marvin Minsky Haskell Programming Assignment A Haskell programming
More informationLecture 8: Summary of Haskell course + Type Level Programming
Lecture 8: Summary of Haskell course + Type Level Programming Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 31, 2017 Principles from Haskell
More informationPROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions
PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product
More informationAn introduction to functional programming. July 23, 2010
An introduction to functional programming July 23, 2010 About Outline About About What is functional programming? What is? Why functional programming? Why? is novel. is powerful. is fun. About A brief
More informationCIS 194: Homework 4. Due Wednesday, February 18, What is a Number?
CIS 194: Homework 4 Due Wednesday, February 18, 2015 What is a Number? This may sound like a deep, philosophical question, but the Haskell type system gives us a simple way to answer it. A number is any
More informationCS 440: Programming Languages and Translators, Spring 2019 Mon
Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed
More informationCSC324 Principles of Programming Languages
CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 21, 2018 Last Class Types terminology Haskell s type system Currying Defining types Value constructors Algebraic data
More informationCS 457/557: Functional Languages
CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is
More informationCSCE 314 Programming Languages
CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as
More informationTesting. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences]
Testing Advanced functional programming - Lecture 2 Wouter Swierstra and Alejandro Serrano 1 Program Correctness 2 Testing and correctness When is a program correct? 3 Testing and correctness When is a
More informationCSE 3302 Programming Languages Lecture 8: Functional Programming
CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative
More informationFunctional Programming TDA 452, DIT 142
Chalmers Göteborgs Universitet 2016-04-07 Examiner: David Sands dave@chalmers.se. Answering questions on the day of the exam (at approx 15.00): Gregoire Detrez (tel: 073 55 69 550) and at other times by
More informationCS 11 Haskell track: lecture 1
CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of
More informationMore fun with recursion
Informatics 1 Functional Programming Lecture 6 More fun with recursion Don Sannella University of Edinburgh Part I Counting Counting Prelude [1..3] [1,2,3] Prelude enumfromto 1 3 [1,2,3] [m..n] stands
More informationD7020E. Robust and Energy-Efficient Real-Time Systems D7020E. Lecture 2: Components & the Timber language
Robust and Energy-Efficient Real-Time Systems Lecture 2: Components & the Timber language 1 1 Recall The dynamic evolution of a system... with offset asynchronous calls synchronous call T T blocked buffered
More informationD7020E. The dynamic evolution of a system Robust and Energy-Efficient Real-Time Systems. blocked Lecture 2: Components & the Timber language.
Recall The dynamic evolution of a system Robust and Energy-Efficient Real-Time Systems with offset asynchronous calls synchronous call T T blocked Lecture 2: Components & the Timber language buffered??
More informationLecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]
1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,
More informationData types for mcrl2
Data types for mcrl2 Aad Mathijssen April 5, 2018 We provide a syntax for the standard data types of the mcrl2 language. This syntax is intended to be a practical mix between standard mathematical notation
More informationChapter 11 :: Functional Languages
Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative
More informationCIS 194: Homework 6. Due Wednesday, 4 March. Fibonacci numbers. It s all about being lazy.
CIS 194: Homework 6 Due Wednesday, 4 March It s all about being lazy. Fibonacci numbers The Fibonacci numbers F n are defined as the sequence of integers, beginning with 1 and 1, where every integer in
More informationHaskell An Introduction
Haskell An Introduction What is Haskell? General purpose Purely functional No function can have side-effects IO is done using special types Lazy Strongly typed Polymorphic types Concise and elegant A First
More informationHaskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder
Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted
More informationCSCE 314 Programming Languages
CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,
More informationData Types The ML Type System
7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let
More information1 The smallest free number
1 The smallest free number Introduction Consider the problem of computing the smallest natural number not in a given finite set X of natural numbers. The problem is a simplification of a common programming
More informationDeclaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany
Declaring Numbers Bernd Braßel, Frank Huch and Sebastian Fischer Department of Computer Science, University of Kiel, Germany WFLP 2007, Paris, France I m going to present joint work with my colleagues
More informationHaskell Making Our Own Types and Typeclasses
Haskell Making Our Own Types and Typeclasses http://igm.univ-mlv.fr/~vialette/?section=teaching Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée January 13, 2015 Making Our Own Types and Typeclasses
More informationEDAF40. 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.
EDAF40 2nd June 2017 14: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. DO NOT WRITE WITH OTHER COLOUR THAN BLACK - coloured text
More informationC++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5
C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................
More informationLogic - CM0845 Introduction to Haskell
Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester
More informationHaskell Overview II (2A) Young Won Lim 8/9/16
(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts
More informationHaskell: From Basic to Advanced. Part 3 A Deeper Look into Laziness
Haskell: From Basic to Advanced Part 3 A Deeper Look into Laziness Haskell is a lazy language Laziness again A particular function argument is only evaluated when it is needed, and if it is needed then
More informationAdvanced Topics in Programming Languages Lecture 2 - Introduction to Haskell
Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Ori Bar El Maxim Finkel 01/11/17 1 History Haskell is a lazy, committee designed, pure functional programming language that
More informationExplicit Recursion in Generic Haskell
Explicit Recursion in Generic Haskell Andres Löh Universiteit Utrecht andres@cs.uu.nl 26th March 2003 This is joint work with Dave Clarke and Johan Jeuring. Overview What is Generic Haskell? The difference
More informationFunctional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph
Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search
More informationHaskell & functional programming, some slightly more advanced stuff. Matteo Pradella
Haskell & functional programming, some slightly more advanced stuff Matteo Pradella pradella@elet.polimi.it IEIIT, Consiglio Nazionale delle Ricerche & DEI, Politecnico di Milano PhD course @ UniMi - Feb
More informationType Classes and Instance Chains: A Relational Approach. John Garrett Morris
Type Classes and Instance Chains: A Relational Approach by John Garrett Morris A dissertation submitted in partial fulfillment of the requirements for the degree of Doctor of Philosophy in Computer Science
More information(Refer Slide Time: 4:00)
Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional
More informationPROGRAMMING IN HASKELL. Chapter 2 - First Steps
PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited
More informationType-indexed functions in Generic Haskell
Type-indexed functions in Generic Haskell Johan Jeuring September 15, 2004 Introduction Today I will talk about: a Types of polymorphism. b Type-indexed functions. c Dependencies. Read about b, and c in
More informationSimon Peyton Jones Microsoft Research August 2013
Simon Peyton Jones Microsoft Research August 2013 reverse :: a. [a] -> [a] xs :: [Bool] foo :: [Bool] foo = reverse xs Instantiate reverse with a unification variable, standing for an as-yet-unknown type.
More informationChapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction
Topics Chapter 15 Functional Programming Reduction and Currying Recursive definitions Local definitions Type Systems Strict typing Polymorphism Classes Booleans Characters Enumerations Tuples Strings 2
More information