PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.

Slides:



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

Programming Languages
Kathleen Fisher cs242 Reading: “A history of Haskell: Being lazy with class”,A history of Haskell: Being lazy with class Section 6.4 and Section 7 “Monads.
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 =
Recursive Data Types Koen Lindström Claessen. Modelling Arithmetic Expressions Imagine a program to help school-children learn arithmetic, which presents.
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.
Cse536 Functional Programming 1 6/12/2015 Lecture #7, Oct. 18, 2004 Today’s Topics – Trees – Kinds of trees - branching factor –functions over trees –patterns.
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.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Advanced Programming Handout 5 Recursive Data Types (SOE Chapter 7)
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
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.
1 COMP313A Programming Languages Functional Programming (7)
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
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.
Chapter Fifteen: Functional Programming Languages Lesson 12.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
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,
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
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.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
© 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.
Polymorphic Functions
String is a synonym for the type [Char].
Conditional Expressions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Koen Lindström Claessen
ML: a quasi-functional language with strong typing
Functions and patterns
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
6.001 SICP Further Variations on a Scheme
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
Records and Type Classes
Functions and patterns
Functions and patterns
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Records and Type Classes
Presentation transcript:

PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language

PrasadCS7762 Modelling Alternatives New data types are useful to model values with several alternatives. Example: Recording phone calls. type History = [(Event, Time)] type Time = Int data Event = Call String | Hangup The number called. E.g. Call ” ”, Hangup, etc.

PrasadCS7763 Extracting a List of Calls We can pattern match on values with components as usual. Example: Extract a list of completed calls from a list of events. calls :: History -> [(String, Time, Time)] calls ((Call number, start) : (Hangup, end) : history) = (number, start, end) : calls history calls [(Call number, start)] = [] -- a call is going on now calls [] = []

PrasadCS7764 Defining Recursive Data Types data Tree a = Node a (Tree a) (Tree a) | Leaf deriving Show Enables us to define polymorphic functions which work on a tree with any type of labels. Types of the components.

PrasadCS7765 Tree Insertion insertTree :: Ord a => a -> Tree a -> Tree a insertTree x Leaf = Node x Leaf Leaf insertTree x (Node y l r) | x < y = Node y (insertTree x l) r | x > y = Node y l (insertTree x r) | x==y = Node y l r Pattern matching works as for lists. Additional requirement

PrasadCS7766 Modelling Expressions Let’s design a datatype to model arithmetic expressions -- not their values, but their structure. An expression can be: a number n a variable x an addition a+b a multiplication a*b data Expr = NumInt |VarString |AddExpr Expr |MulExpr Expr A recursive data type !!

PrasadCS7767 Symbolic Differentiation Differentiating an expression produces a new expression. derive :: Expr -> String -> Expr derive (Num n) x = Num 0 derive (Var y) x | x==y = Num 1 | x/=y = Num 0 derive (Add a b) x = Add (derive a x) (derive b x) derive (Mul a b) x = Add (Mul a (derive b x)) (Mul b (derive a x)) Variable to differentiate w.r.t.

PrasadCS7768 Example d (2*x) = 2 dx derive (Mul (Num 2) (Var ”x”)) ”x” Add (Mul (Num 2) (derive (Var ”x”) ”x”)) (Mul (Var ”x”) (derive (Num 2) ”x”)) Add (Mul (Num 2) (Num 1)) (Mul (Var ”x”) (Num 0)) 2*1 + x*0

PrasadCS7769 Formatting Expressions Expressions will be more readable if we convert them to strings. formatExpr (Mul (Num 1) (Add (Num 2) (Num 3))) ”1*2+3” formatExpr :: Expr -> String formatExpr (Num n)= show n formatExpr (Var x)= x formatExpr (Add a b)= formatExpr a ++ ”+” ++ formatExpr b formatExpr (Mul a b)= formatExpr a ++ ”*” ++ formatExpr b

PrasadCS77610 Quiz Which brackets are necessary?1+(2+3) 1+(2*3) 1*(2+3) What kind of expression may need to be bracketed? When does it need to be bracketed? NO! YES! NO! Additions Inside multiplications.

PrasadCS77611 Idea Give formatExpr an extra parameter, to tell it what context its argument appears in. data Context = Multiply | AnyOther formatExpr (Add a b) Multiply = ”(” ++ formatExpr (Add a b) AnyOther ++ ”)” formatExpr (Mul a b) _ = formatExpr a Multiply ++ ”*” ++ formatExpr b Multiply

PrasadCS77612 ADT and Modules

PrasadCS77613 module construct in Haskell Enables grouping a collection of related definitions Enables controlling visibility of names –export public names to other modules –import names from other modules disambiguation using fully qualified names Enables defining Abstract Data Types

PrasadCS77614 module MTree ( Tree(Leaf,Branch), fringe ) where data Tree a = Leaf a | Branch (Tree a) (Tree a) fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = fringe left ++ fringe right This definition exports all the names defined in the module including Tree -constructors.

PrasadCS77615 module Main (main) where import MTree ( Tree(Leaf,Branch), fringe ) main = do print (fringe (Branch (Leaf 1) (Leaf 2)) ) Main explicitly imports all the names exported by the module MTree.

PrasadCS77616 module Fringe(fringe) where import Tree(Tree(..)) fringe :: Tree a -> [a] -- A different definition of fringe fringe (Leaf x) = [x] fringe (Branch x y) = fringe x module QMain where import Tree ( Tree(Leaf,Branch), fringe ) import qualified Fringe ( fringe ) qmain = do print (fringe (Branch (Leaf 1) (Leaf 2))) print(Fringe.fringe(Branch (Leaf 1) (Leaf 2)) )

PrasadCS77617 Abstract Data Types module TreeADT (Tree, leaf, branch, cell, left, right, isLeaf) where data Tree a = Leaf a | Branch (Tree a) (Tree a) leaf = Leaf branch = Branch cell (Leaf a) = a left (Branch l r) = l right (Branch l r) = r isLeaf (Leaf _) = True isLeaf _ = False

PrasadCS77618 Other features Selective hiding import Prelude hiding length Eliminating functions inherited on the basis of the representation. module Queue( … operation names... ) where newtype Queue a = MkQ ([a],[a]) … operation implementation… –Use of MkQ -constructor prevents equality testing, printing, etc of queue values.

PrasadCS77619 Treatment of Overloading through Type/Class Hierarchy

PrasadCS77620 Kinds of functions Monomorphic (defined over one type) capitalize : Char -> Char Polymorphic (defined similarly over all types) length : [a] -> Int Overloaded (defined differently and over many types) (==) : Char -> Char -> Bool (==) : [(Int,Bool]] -> [(Int,Bool]] -> Bool

PrasadCS77621 Overloading problem in SML fun add x y = x + y SML-90 treats this definition as ambiguous: int -> int -> int real -> real -> real SML-97 defaults it to: int -> int -> int Ideally, add defined whenever + is defined on a type. add :: (hasPlus a) => a -> a -> a

PrasadCS77622 Parametric vs ad hoc polymorphism Polymorphic functions use the same definition at each type. Overloaded functions may have a different definition at each type. class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x/=y = not (x==y) Class name. Class methods and types. Default definition. Read: “ a is a type in class Eq, if it has the following methods”.

PrasadCS77623 Class Hierarchy and Instance Declarations class Eq a => Ord a where ( =),(>) :: a -> a -> Bool max, min :: a -> a -> a Read: “Type a in class Eq is also in class Ord, if it provides the following methods…” instance Eq Integer where x==y = … primitive … instance Eq a => Eq [a] where [] == [] = True x:xs == y:ys = x == y && xs == ys If a is in class Eq, then [a] is in class Eq, with the method definition given.

PrasadCS77624 Types of Overloaded Functions insert :: Ord a => a -> [a] -> [a] insert x [] = [] insert x (y:xs) | x<=y = x:y:xs | x>y = y:insert x xs a may be any type in class Ord. Because insert uses a method from class Ord. f :: (Eq a) => a -> [a] -> Int f x y = if x==y then 1 else 2

PrasadCS77625 Show and Read class Show a where show :: a -> String class Read a where read :: String -> a These are definitions are simplifications: there are more methods in reality. read. show = id (usually)

PrasadCS77626 Derived Instances data Tree a = Node a (Tree a) (Tree a) | Leaf deriving (Eq, Show) Constructs a “default instance” of class Show. Works for standard classes. Main> show (Node 1 Leaf (Node 2 Leaf Leaf)) "Node 1 Leaf (Node 2 Leaf Leaf)"

PrasadCS77627 Multi-Parameter Classes Define relations between classes. class Collection c a where empty :: c add :: a -> c -> c member :: a -> c -> Bool c is a collection with elements of type a. instance Eq a => Collection [a] a where empty = [] add = (:) member = elem instance Ord a => Collection (Tree a) a where empty = Leaf add = insertTree member = elemTree

PrasadCS77628 Multiple Inheritance class (Ord a, Show a) => a where … SortAndPrint function … Advanced Features: Module, … ADT, …

PrasadCS77629 Functional Dependencies class Collection c a | c -> a where empty :: c add :: a -> c -> c member :: a -> c -> Bool A functional dependency Declares that c determines a : there can be only one instance for each type c. Helps the type-checker resolve ambiguities (tremendously). add x (add y empty) -- x and y must be the same type.

PrasadCS77630 class MyFunctor f where tmap :: (a -> b) -> f a -> f b data Tree a = Branch (Tree a) (Tree a) | Leaf a deriving Show instance MyFunctor Tree where tmap f (Leaf x) = Leaf (f x) tmap f (Branch t1 t2) = Branch (tmap f t1) (tmap f t2) tmap (*10) (Branch (Leaf 1) (Leaf 2))

PrasadCS77631 Higher-Order Functions Functions are values in Haskell. “Program skeletons” take functions as parameters. takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x:takeWhile p xs | otherwise = [] Takes a prefix of a list, satisfying a predicate.

PrasadCS77632 More Ways to Denote Functions below a b = b < a takeWhile (below 10) [1,5,9,15,20] takeWhile (\b -> b < 10) [1,5,9,15,20] takeWhile (<10) [1,5,9,15,20] “Lambda” expression. Function definition in place. Partial operator application -- argument replaces missing operand.

PrasadCS77633 Lazy Evaluation Expressions are evaluated only when their value is really needed! Function arguments, data structure components, are held unevaluated until their value is used. fib = 1 : 1 : [ a+b | (a,b)<- zip fib (tail fib) ] nats = 0 : map (+1) nats

PrasadCS77634 Non-strict / Lazy Functional Language Parameter passing mechanism –Call by name –Call by need ( but not Call by value ) Advantages –Does not evaluate arguments not required to determine the final value of the function. –“Most likely to terminate” evaluation order. fun const x = 0; const (1/0) = 0;

PrasadCS77635 Practical Benefits –Frees programmer from worrying about control issues: Best order for evaluation … To compute or not to compute a subexpression … –Facilitates programming with potentially infinite value or partial value. Costs –Overheads of building thunks to represent delayed argument.