Functions and patterns

Slides:



Advertisements
Similar presentations
Higher-order functions in ML
Advertisements

A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Higher-order functions in OCaml. Higher-order functions A first-order function is one whose parameters and result are all "data" A second-order function.
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 =
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.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
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,
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.
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.
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.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
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.
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.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
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.
Lecture 14: Advanced Topic: Functional Programming
Polymorphic Functions
Functional Programming
Conditional Expressions
Recursion.
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Theory of Computation Lecture 4: Programs and Computable Functions II
Haskell Chapter 2.
PROGRAMMING IN HASKELL
Functions and patterns
A lightening tour in 45 minutes
Expanded Recursive Diagrams OCAML rapid tour, day 2
Functional Programming
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Fundamentals of Functional Programming
HIGHER ORDER FUNCTIONS
Functions and patterns
PROGRAMMING IN HASKELL
Functional Programming
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

Functions and patterns Haskell II Functions and patterns 5-May-19

Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool && || not Lists : ++ head tail last init take Tuples fst snd Polymorphic: < <= == /= => > show

User-Defined Data Types data Color = Red | Blue toString Red = "red" toString Blue = "blue" data Tree a = Leaf a | Branch (Tree a) (Tree a) Can be tricky to use

It’s all about types! Getting the types right is critical to programming in Haskell In GHCi, :type x or :t x will tell you the type of x GHCi> :t "abc" "abc" :: [Char] The :: can be read as “has the type” [Char] is the representation for “list of char” Is "abc" really a list of characters? GHCi> :t ['a', 'b', 'c'] ['a', 'b', 'c'] :: [Char] GHCi> ['a', 'b', 'c'] == "abc" True

More type definitions GHCi> :t ["ab", "cd"] ["ab", "cd"] :: [[Char]] [[Char]] is a list of lists of characters = a list of strings GHCi> :t [] [] :: [a] Here, a is a “type variable”—[] could be a list of any type GHCi> :t [[]] [[]] :: [[a]] [[a]] is a list of lists, all of which have the same type GHCi> :t head head :: [a] -> a head takes a list of any type a and returns a single value of type a

Type restrictions GHCi> :t even even :: Integral a => a -> Bool Integral a is a type restriction—it says a must be some Integral type The -> indicates a function; in this case, a function from some type a (restricted to be integral) to a Boolean. GHCi> :t (5, 'a', "abc") (5, 'a', "abc") :: Num t => (t, Char, [Char]) (5, 'a', "abc") is a tuple consisting of a Numeric type t, a Character, and a string (list of Char) Unlike lists, tuples can (and often do) contain values of different types

Types of functions GHCi> :t mod mod :: Integral a => a -> a -> a GHCi> mod 20 6 2 GHCi> 20 `mod` 6 2 Functions in Haskell take a single argument a -> a -> a associates as (a -> a) -> a GHCi> (mod 20) 6 2 GHCi> :t (mod 20) (mod 20) :: Integral a => a -> a

Types of higher-order functions GHCi> :t map map :: (a -> b) -> [a] -> [b] GHCi> :t flip flip :: (a -> b -> c) -> b -> a -> c GHCi> flip map [1, 2, 3, 4] even [False,True,False,True] GHCi> :t flip map flip map :: [a] -> (a -> b) -> [b] compare this with map :: (a -> b) -> [a] -> [b]

Assorted Syntax Comments are -- to end of line or {- to -} (these may be nested) Types are capitalized, variables are not Indentation may be used in place of braces Infix operators: + - `mod` `not` Prefix operators: (+) (-) mod not Types: take :: Int -> [a] -> [a]

Layout Grouping is done by indentation, not by braces or parentheses Actually, braces can be used, but that’s unusual The first nonblank character following where, let, or of determines the starting column let x = a + b y = a * b in y / x Every expression in the same group must begin in the same column Make sure your text editor replaces tabs with spaces

Infinite Lists [1..5] == [1, 2, 3, 4, 5] [1..] == all positive integers [5, 10..32] == [5, 10, 15, 20, 25, 30] [5, 10..] == positive multiples of 5 [x*x | x <- [1..]] == squares of positive integers [x*x | x <- [1..], even x] == squares of positive even integers [(x, y) | x <- [1..10], y <- [1..10], x < y]

Functions are also data Functions are “first-class objects” Functions can be assigned Functions can be passed as parameters Functions can be stored in data structures There are operations on functions But functions can’t be tested for equality Theoretically very hard!

Anonymous Functions Form is \ parameters -> body Example: \x y -> (x + y) / 2 the \ is pronounced “lambda” the x and y are the formal parameters inc x = x + 1 this is shorthand for inc = \x -> x + 1 add x y = x + y this is shorthand for add = \x y -> x + y

Currying Technique named after Haskell Curry Functions only need one argument Currying absorbs an argument into a function f a b = (f a) b, where (f a) is a curried function (avg 6) 8 7.0

Slicing Functions may be “partially applied” inc x = x + 1 can be defined instead as inc = (+ 1) add x y = x + y can be defined instead as add = (+) negative = (< 0)

Point free style Functions that take parameters (“points”) can be written as functions with implicit parameters GHCi> let square_all xs = map (\x -> x^2) xs GHCi> square_all [1, 2, 3, 4, 5] [1,4,9,16,25] GHCi> let square_all = map (\x -> x^2) GHCi> square_all [1, 2, 3, 4, 5] [1,4,9,16,25] GHCi> let square_all = map (^2) Point free style can result in easier to read, less cluttered code It can also result in obscure code, so use with care

map map :: (a -> b) -> [a] -> [b] applies the function to all elements of the list Prelude> map odd [1..5] [True,False,True,False,True] Prelude> map (* 2) [1..5] [2,4,6,8,10]

filter filter :: (a -> Bool) -> [a] -> [a] Returns the elements that satisfy the test Prelude> filter even [1..10] [2,4,6,8,10] Prelude> filter (\x -> x>3 && x<10) [1..20] [4,5,6,7,8,9]

iterate iterate :: (a -> a) -> a -> [a] f x returns the list [x, f x, f f x, f f f x, …] Prelude> take 8 (iterate (2 *) 1) [1,2,4,8,16,32,64,128] Prelude> iterate tail [1..3] [[1,2,3],[2,3],[3],[], *** Exception: Prelude.tail: empty list

foldl foldl :: (a -> b -> a) -> a -> [b] -> a foldl f i x starts with i, repeatedly applies f to i and the next element in the list x Prelude> foldl (-) 100 [1..3] 94 94 = 100 - 1 - 2 - 3

foldl1 foldl1 :: (a -> a -> a) -> [a] -> a Same as: foldl f (head x) (tail x) Prelude> foldl1 (-) [100, 1, 2, 3] 94 Prelude> foldl1 (+) [1..100] 5050

flip flip :: (a -> b -> c) -> b ->a -> c Reverses first two arguments of a function Prelude> elem 'o' "aeiou" True Prelude> flip elem "aeiou" 'o' Prelude> (flip elem) "aeiou" 'o'

Function composition with (.) (.) :: (a -> b) -> (c -> a) -> (c -> b) (f . g) x is the same as f (g x) double x = x + x quadruple = double . double doubleFirst = (* 2) . head Main> quadruple 3 12 Main> doubleFirst [3..10] 6

span span :: (a -> Bool) -> [a] -> ([a], [a]) Break the lists into two lists those at the front that satisfy the condition the rest Main> span (<= 5) [1..10] ([1,2,3,4,5],[6,7,8,9,10]) Main> span (< 'm') "abracadabra" ("ab","racadabra")

break break :: (a -> Bool) -> [a] -> ([a], [a]) Break the lists into two lists those at the front that fail the condition the rest Main> break (== ' ') "Haskell is neat!" ("Haskell"," is neat!")

Function Definition I Functions are defined with = fact :: Int -> Int -- explicit type fact n = if n == 0 then 1 else n * fact (n - 1) There is no requirement that you explicitly state the type of each function you define Haskell is superb at inferring the types of functions Using Hadley-Milner type inference However: All experienced Haskell programmers do explicitly state the type of each function Doing so catches almost all programming errors! Haskell programming is all about getting the types right

Function Definition II Functions are usually defined by cases fact :: Int -> Int fact n | n == 0 = 1 | otherwise = n * fact (n - 1) fact :: Int -> Int fact n = case n of 0 -> 1 n -> n * fact (n - 1) These are equivalent definitions

Function Definition III You can separate the cases with “patterns” fact :: Int -> Int fact 0 = 1 fact n = n * fact (n - 1) How does this work?

Pattern Matching Functions cannot in general be overloaded But they can be broken into cases Each case must have the same signature fact :: Int -> Int -- explicit signature fact 0 = 1 fact n = n * fact (n - 1) fact 5 won’t match the first, but will match the second

Pattern Types I A variable will match anything A wildcard, _, will match anything, but you can’t use the matched value A constant will match only that value Tuples will match tuples, if same length and constituents match Lists will match lists, if same length and constituents match However, the pattern may specify a list of arbitrary length

Pattern Types II (h:t) will match a nonempty list whose head is h and whose tail is t second (h:t) = head t Main> second [1..5] 2

Pattern Types III “As-patterns” have the form w@pattern When the pattern matches, the w matches the whole of the thing matched firstThree all@(h:t) = take 3 all Main> firstThree [1..10] [1,2,3]

Pattern Types IV (n+k) matches any value equal to or greater than k; n is k less than the value matched silly (n+5) = n Main> silly 20 15 This is the only arithmetical pattern; it does not generalize to any other pattern

Advantages of Haskell Extremely concise Easy to understand no, really! No core dumps Polymorphism improves chances of re-use Powerful abstractions Built-in memory management

Disadvantages of Haskell Unfamiliar Slow because compromises are less in favor of the machine

quicksort quicksort [] = [] quicksort (x:xs) = quicksort [y | y <- xs, y < x] ++ [x] ++ quicksort [y | y <- xs, y >= x]

The End