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.

Slides:



Advertisements
Similar presentations
Lecture 9 Polymorphism, Overloading and Higher Order Functions 1 Polymorphism and Overloading.
Advertisements

ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Chapter 6 Shapes III: Perimeters of Shapes. The Perimeter of a Shape  To compute the perimeter we need a function with four equations (1 for each Shape.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
Comp 205: Comparative Programming Languages Functional Programming Languages: Haskell Lecture notes, exercises, etc., can be found at:
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/10/2015 Lecture #6, Oct 13, 2004 Reading Assignments –Read chapter 5 of the Text Polymorphic and Higher-Order Functions.
Cse536 Functional Programming 1 6/10/2015 Lecture #8, Oct. 20, 2004 Todays Topics –Sets and characteristic functions –Regions –Is a point in a Region –Currying.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Chapter 2 A Module of Shapes: Part I. Defining New Datatypes  The ability to define new data types in a programming language is important.  Kinds of.
Advanced Programming Handout 4. Introductions  Me: Benjamin C. Pierce (known as Benjamin, or, if you prefer, Dr. Pierce, but not Ben or Professor) 
Chapter 5 Polymorphic and Higher-Order Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
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,
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.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Operators, Functions and Modules1 Pattern Matching & Recursion.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
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.
Modeling with Haskell Scientific Seminar 03/04 Gerhard Navratil.
Overview of the Haskell 98 Programming Language
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
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,
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
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.
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Polymorphic Functions
Conditional Expressions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
Functions and patterns
A lightening tour in 45 minutes
Haskell.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes in Haskell
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Higher Order Functions
PROGRAMMING IN HASKELL
CSE-321 Programming Languages Introduction to Functional Programming
Functions and patterns
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Functions and patterns
PROGRAMMING IN HASKELL
2016 | 10 OCT SUN MON TUE WED THU FRI SAT
PROGRAMMING IN HASKELL
Presentation transcript:

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 Topics –Useful functions on lists »The prelude functions –Strings and Characters –Lazy Evaluation »Infinite Lists –Data-Type declarations –Defining functions over datatypes using patterns –Enumerations –The Shape Datatype of the text

Cse536 Functional Programming 2 6/28/2015 Useful Functions on lists Inspect the Haskell Prelude for a complete listHaskell Prelude Let x = [1,2,3,4] y = ["a","b","c","d"] Pair-wise destructors head x = 1 tail x = [2,3,4] init x = [1,2,3] last x = 4 take 2 x = [1,2] drop 2 x = [3,4] takeWhile odd x = [1] dropWhile odd x = [2,3,4] Useful Auxiliary reverse x = [4,3,2,1] zip x y = [(1,"a"), (2,"b"), (3,"c"), (4,"d")]

Cse536 Functional Programming 3 6/28/2015 Useful Functions on lists Higher Order Functions Let: x = [1,2,3,4] y = ["a","b","c","d"] Then: map f x = [f 1, f 2, f 3, f 4] filter even x = [2,4] foldr (+) e x = 1 + (2 + (3 + (4 + e))) foldl (+) e x = (((e + 1) + 2) + 3) + 4 iterate f 1 = [1, f 1, f(f 1),f(f(f 1)),... ]

Cse536 Functional Programming 4 6/28/2015 String and Char String is defined to be a (List Char) ? "abc" abc ? ['a', 'b', 'c'] abc Be Careful !! Know the difference between: –"a" is a string (A List of Char with one element) –'a' is a Char –`a` is an operator (note the back-quotes) Since String = List Char all the list operations work on strings ? “abc” ++ “xyz” abcxyz ? reverse “abc” cba

Cse536 Functional Programming 5 6/28/2015 Quotation Mechanisms The normal (C-like) back-slash notation is used to embed special characters in String's and Char's ':' colon '\'' single quote '\"' double quote '\\' back-slash '\n' newline '\t' tab They can also be used in String's "A two \n line string" Conversion Functions ord :: Char -> Int chr :: Int -> Char Lots of interesting functions in the prelude.

Cse536 Functional Programming 6 6/28/2015 Lazy Evaluation (GITH pp 12-14) Consider: repeat x = x : (repeat x) ? repeat 't' “tttttttttttttttttttttttttttttttttttttttttttttttttttttt ^C{Interrupted!} Ok to use a finite Prefix ? take 10 (repeat 't') “tttttttttt” Remember iterate? ? take 5 (iterate (+1) 1) [1, 2, 3, 4, 5] ? take 5 (iterate (*2) 1) [1, 2, 4, 8, 16] ? take 5 (iterate (/10) 142) [142, 14, 1, 0, 0]

Cse536 Functional Programming 7 6/28/2015 Approximating the square root. –Compute the n+1 approximation from the nth approximation of square root of X –a n+1 = ( a n + N / a n ) / 2 The Haskell function next n a = (a + (n/a) )/ 2.0 Example Use ? take 7 (iterate (next 2.0) 1.0) [1.0, 1.5, , , , , ] How do we know when to stop? [1.0, 1.5, , , Computing Square Root

Cse536 Functional Programming 8 6/28/2015 Small Changes Chop off a list when two successive elements are within some small epsilon of each other. within eps (a : b : rest) = if abs( (a/b) -1.0 ) <= eps then b else within eps (b : rest) Now square root is easy ? within (iterate (next 2.0) 1.0)

Cse536 Functional Programming 9 6/28/2015 Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes –enumerated types –records (or products or struct) –variant records (or sums) –pointer types –arrays Haskell’s data declaration provides many of these kinds of types in a uniform way which abstracts from their implementation details. The data declaration defines new functions and constants, which provide an abstract interface to the newly defined type.

Cse536 Functional Programming 10 6/28/2015 The Data Declaration Enumeration Types data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat deriving Eq The names on right hand side are constructor constants and are the only elements of the type. valday 0 = Sun valday 1 = Mon valday 2 = Tue valday 3 = Wed valday 4 = Thu valday 5 = Fri valday 6 = Sat ? valday 3 Wed

Cse536 Functional Programming 11 6/28/2015 Constructors & Patterns data defined types define new constructors and can be accessed by patterns. Constructors without arguments are constants Example using case dayval x = case x of Sun -> 0 Mon -> 1 Tue -> 2 Wed -> 3 ; Thu -> 4 ; Fri -> 5 Sat -> 6 Note: Indentation bounds each clause ( pat -> body ) in case, or use a semi-colon rather than indentation.

Cse536 Functional Programming 12 6/28/2015 Patterns in Declarations In a declaration patterns can be used. Possible to have many lines for a definition if each pattern is distinct. dayval Sun = 0 dayval Mon = 1 dayval Tue = 2 dayval Wed = 3 dayval Thu = 4 dayval Fri = 5 dayval Sat = 6 ? dayval Tue 2

Cse536 Functional Programming 13 6/28/2015 Patterns are not always necessary An alternate definition might be dayval :: Day -> Int dayval x = let (d,n) = head (filter (\(d,n)->d==x) (zip [Sun,Mon,Tue,Wed,Thu,Fri,Sat] [0..])) in n Note use of [0..] –[0..] denotes [0,1,2,3,... ] Why is an infinite list possible here? Give a definition of zip using patterns over lists ([] and (x:xs) zip =

Cse536 Functional Programming 14 6/28/2015 Example function dayafter d = valday (((dayval d) + 1) `mod` 7) ? dayafter Tue Wed

Cse536 Functional Programming 15 6/28/2015 Other Enumeration Examples data Move = Paper | Rock | Scissors beats :: Move -> Move beats Paper = Scissors beats Rock = Paper beats Scissors = Rock ? beats Paper Scissors data Bool = True | False data Direction = North | East | South | West

Cse536 Functional Programming 16 6/28/2015 Variant Records More complicated types data Tagger = Tagn Int | Tagb Bool NOTE: the types of the constructors are functions (not constants as for enumerated types) Tagb :: Bool -> Tagger Tagn :: Int -> Tagger As for all constructors: (Tagn 12) »1) Cannot be simplified. We say it is Canonical »2) Can be used in a pattern on the left hand side of an =

Cse536 Functional Programming 17 6/28/2015 Example functions on Tagger number (Tagn n) = n boolean (Tagb b) = b isNum (Tagn _) = True isNum (Tagb _) = False ? :t number number :: Tagger -> Int ? number (Tagn 3) 3 ? isNum (Tagb False) False

Cse536 Functional Programming 18 6/28/2015 Another Variant Record-like Type data Temp = Celsius Float | Fahrenheit Float | Kelvin Float Use patterns to define functions over this type: toKelvin (Celsius c) = Kelvin(c ) toKelvin (Fahrenheit f) = Kelvin( (f ) * (5.0/9.0) ) toKelvin (Kelvin k) = Kelvin k

Cse536 Functional Programming 19 6/28/2015 Shape types from the Text data Shape = Rectangle Float Float | Ellipse Float Float | RtTriangle Float Float | Polygon [ (Float,Float) ] deriving Show Deriving Show –tells the system to build an show function for the type Shape Using Shape - Functions returning shape objects circle radius = Ellipse radius radius square side = Rectangle side side

Cse536 Functional Programming 20 6/28/2015 Functions over Shape Functions over shape can be defined using pattern matching area :: Shape -> Float area (Rectangle s1 s2) = s1 * s2 area (Ellipse r1 r2) = pi * r1 * r2 area (RtTriangle s1 s2) = (s1 *s2) / 2 area (Polygon (v1:pts)) = polyArea pts where polyArea :: [ (Float,Float) ] -> Float polyArea (v2 : v3 : vs) = triArea v1 v2 v3 + polyArea (v3:vs) polyArea _ = 0 Note use of prototype Note use of nested patterns Note use of wild card pattern (matches anything)

Cse536 Functional Programming 21 6/28/2015 A B C D E F Poly = [A,B,C,D,E,F] Area = Area(Triangle [A,B,C]) + Area(Poly[A,C,D,E,F])

Cse536 Functional Programming 22 6/28/2015 TriArea triArea v1 v2 v3 = let a = distBetween v1 v2 b = distBetween v2 v3 c = distBetween v3 v1 s = 0.5*(a+b+c) in sqrt (s*(s-a)*(s-b)*(s-c)) distBetween (x1,y1) (x2,y2) = sqrt ((x1-x2)^2 + (y1-y2)^2)