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

Similar documents
Shell CSCE 314 TAMU. Haskell Functions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Shell CSCE 314 TAMU. Functions continued

INTRODUCTION TO FUNCTIONAL PROGRAMMING

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

A general introduction to Functional Programming using Haskell

Lecture 19: Functions, Types and Data Structures in Haskell

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

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

An introduction introduction to functional functional programming programming using usin Haskell

Standard prelude. Appendix A. A.1 Classes

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

CS 457/557: Functional Languages

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

CS 320: Concepts of Programming Languages

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

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

CSc 372 Comparative Programming Languages

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

Shell CSCE 314 TAMU. Higher Order Functions

CSCE 314 Programming Languages

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

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

Functional Programming in Haskell for A level teachers

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

INTRODUCTION TO HASKELL

Background Operators (1E) Young Won Lim 7/7/18

CSCE 314 Programming Languages

Functional Programming in Haskell Part I : Basics

Lecture 2: List algorithms using recursion and list comprehensions

Imperative languages

CS 320: Concepts of Programming Languages

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Lists. Michael P. Fourman. February 2, 2010

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

Organization of Programming Languages CS3200/5200N. Lecture 11

Higher Order Functions in Haskell

LECTURE 16. Functional Programming

CS 440: Programming Languages and Translators, Spring 2019 Mon

CSc 372. Comparative Programming Languages. 15 : Haskell List Comprehension. Department of Computer Science University of Arizona

Lecture 4: Higher Order Functions

Introduction. chapter Functions

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

CMSC 330: Organization of Programming Languages. Operational Semantics

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Box-and-arrow Diagrams

Informatics 1 Functional Programming Lecture 11. Data Representation. Don Sannella University of Edinburgh

Haskell through HUGS THE BASICS

Functional Programming

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CSCE 314 Programming Languages

SML A F unctional Functional Language Language Lecture 19

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

Chapter 15. Functional Programming Languages

CS 360: Programming Languages Lecture 12: More Haskell

Programming Paradigms

List Functions, and Higher-Order Functions

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

Functional Programming and Haskell

Declaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

CS 11 Haskell track: lecture 1

Programming Language Concepts: Lecture 14

Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Functional Programming. Pure Functional Programming

Putting the fun in functional programming

Introduction to Programming, Aug-Dec 2006

State Monad (3D) Young Won Lim 9/25/17

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

Functional Programming. Big Picture. Design of Programming Languages

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

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

Exercise 1 ( = 22 points)

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

Programming Languages Fall 2013

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Haskell An Introduction

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

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

Programming Languages

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS

List Processing in Ocaml

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

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

Functional Programming Languages (FPL)

Functional Logic Programming Language Curry

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Let s Talk About Logic

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

Chapter 11 :: Functional Languages

Transcription:

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 can be defined using conditional expressions: if cond then e1 else e2 e1 and e2 must be of the same type else branch is always present abs :: Int -> Int abs n = if n >= 0 then n else n max :: Int -> Int -> Int max x y = if x <= y then y else x take :: Int -> [a] -> [a] take n xs = if n <= 0 then [] else if xs == [] then [] else (head xs) : take (n-1) (tail xs)

Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations. abs n n >= 0 = n otherwise = -n Prelude: otherwise = True Guarded equations can be used to make definitions involving multiple conditions easier to read: signum n n < 0 = -1 n == 0 = 0 otherwise = 1 compare with signum n = if n < 0 then -1 else if n == 0 then 0 else 1 4

5 Guarded Equations (Cont.) Guards and patterns can be freely mixed, the first equation whose pattern matches and guard is satisfied is chosen. take :: Int -> [a] -> [a] take n xs n <= 0 = [] take n [] = [] take n (x:xs) = x : take (n-1) xs

6 Pattern Matching Many functions are defined using pattern matching on their arguments. not not False = True :: Bool -> Bool not True = False not maps False to True, and True to False. Pattern can be a constant value, or include one or more variables.

Functions can be defined in many different ways using pattern matching. For example (&&) :: Bool Bool Bool True && True = True True && False = False False && True = False False && False = False can be defined more compactly by True && True = True _ && _ = False However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: False && _ = False True && b = b The underscore symbol _ is a wildcard pattern that matches any argument value. 7

8 Patterns are matched in order. For example, the following definition always returns False: _ && _ = False True && True = True Patterns may not repeat variables. For example, the following definition gives an error: b && b = b _ && _ = False

9 List Patterns Internally, every non-empty list is constructed by repeated use of an operator (:) called cons that adds an element to the start of a list. [1,2,3,4] Means 1:(2:(3:(4:[]))). Functions on lists can be defined using x:xs patterns. head :: [a] a head (x:_) = x tail :: [a] [a] tail (_:xs) = xs head and tail map any non-empty list to its first and remaining elements. is this definition complete?

10 Note: x:xs patterns only match non-empty lists: > head [] Error x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error: head x:_ = x Patterns can contain arbitrarily deep structure: f (_: (_, x):_) = x g [[_]] = True

11 Totality of Functions (Total) function maps every element in the function s domain to an element in its codomain. Partial function maps zero or more elements in the function s domain to an element in its codomain, and can leave some elements undefined. Haskell functions can be partial. For example: head (x:_) = x > head [] *** Exception: Prelude.head: empty list > "10elements"!! 10 *** Exception: Prelude.(!!): index too large

12 Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. λx x+x This nameless function takes a number x and returns the result x+x. The symbol λ is the Greek letter lambda, and is typed at the keyboard as a backslash \. In mathematics, nameless functions are usually denoted using the symbol, as in x x+x. In Haskell, the use of the λ symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based.

13 Why are Lambda's Useful? 1. Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: means add x y = x + y square x = x * x add = \x -> (\y -> x + y) square = \x -> x * x

14 2. Lambda expressions can be used to avoid naming functions that are only referenced once. For example: odds n = map f [0..n-1] where f x = x * 2 + 1 can be simplified to odds n = map (\x -> x * 2 + 1) [0..n-1] 3. Lambda expressions can be bound to a name (function argument) incrementer = \x -> x + 1 add (incrementer 5) 6

15 (1) Case Expressions take m ys = case (m, ys) of (n, _) n <= 0 -> [] (_, []) -> [] (n, x:xs) -> x : take (m-1) xs Pattern matching need not be tied to function definitions; they also work with case expressions. For example: (2) length [] = 0 length (_:xs) = 1 + length xs using a case expression and a lambda: length = \ls -> case ls of [] -> 0 (_:xs) -> 1 + length xs

(1) Let and Where The let and where clauses are used to create a local scope within a function. For example: reserved s = -- using let let keywords = words if then else for while relops = words ==!= < > <= >= eleminany w [] = False eleminany w (l:ls) = w `elem` l eleminany w ls in eleminany s [keywords, relops] (2) reserved s = -- using where eleminany s [keywords, relops] where keywords = words if then else for while... eleminany w (l:ls) = w `elem` l eleminany w ls unzip :: [(a, b)] -> ([a], [b]) unzip [] = ([], []) unzip ((a, b):rest) = let (as, bs) = unzip rest in (a:as, b:bs) 16

17 Let vs. Where The let in is an expression, whereas where blocks are declarations bound to the context. For example: f x -- using where block cond1 x = a cond2 x = g a otherwise = f (h x a) where a = w x f x -- using let-in expression = let a = w x in case () of _ cond1 x -> a cond2 x -> g a otherwise -> f (h x a)

18 Sections An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses. For example: > 1 + 2 3 > (+) 1 2 3 This convention also allows one of the arguments of the operator to be included in the parentheses. For example: > (1+) 2 > (+2) 1 3 3 In general, if is an operator then functions of the form ( ), (x ) and ( y) are called sections.

19 Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: (1+) (1/) (*2) (/2) - successor function (\y->1+y) - reciprocal function - doubling function - halving function Sometimes it is convenient or necessary to pass an operator as a parameter or when stating its type

20 Exercises (1) Consider a function safetail that behaves in the same way as tail, except that safetail maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail using: (a) (b) (c) a conditional expression; guarded equations; pattern matching. Hint: the library function null :: [a] Bool can be used to test if a list is empty.

21 (2) Give three possible definitions for the logical or operator ( ) using pattern matching. (3) Redefine the following version of (&&) using conditionals rather than patterns: True && True = True _ && _ = False (4) Do the same for the following version: True && b = b False && _ = False

22 Outline Defining Functions List Comprehensions Recursion

23 List Comprehensions A convenient syntax for defining lists Set comprehension - In mathematics, the comprehension notation can be used to construct new sets from old sets. E.g., {(x 2,y 2 ) x {1,2,...,10}, y {1,2,...,10}, x 2 +y 2 101} Same in Haskell: new lists from old lists [(x^2, y^2) x <- [1..10], y <- [1..10], x^2 + y^2 <= 101] generates: [(1,1),(1,4),(1,9),(1,16),(1,25),(1,36),(1,49),(1,64),(1,81),(1,1 00),(4,1),(4,4),(4,9),(4,16),(4,25),(4,36),(4,49),(4,64),(4,81),(9,1),(9,4),(9,9),(9,16),(9,25),(9,36),(9,49),(9,64),(9,81),(16,1),(16,4),(16,9),(16,16),(16,25),(16,36),(16,49),(16,64),(16,81),(25,1),(25,4),(25,9),(25,16),(25,25),(25, 36),(25,49),(25,64),(36,1),(36,4),(36,9),(36,16),(36,25),(36,36),(36,49),(36,64),(49,1),(49,4),(49,9),(49,16),(49,25),(49,36),(49,49),(64,1),(64,4),(64,9),(64,16),(64,25),(64,36),(81,1),(81,4),(81,9),(81,16),(100,1)]

List Comprehensions: Generators The expression x <- [1..10] is called a generator, as it states how to generate values for x. generators can be infinite, e.g., > take 3 [x x <- [1..]] [1,2,3] Comprehensions can have multiple generators, separated by commas. For example: > [(x,y) x <- [1,2,3], y <- [4,5]] [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)] Multiple generators are like nested loops, with later generators as more deeply nested loops whose variables change value more frequently. 24

25 For example: > [(x,y) y <- [4,5], x <- [1,2,3]] [(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)] x [1,2,3] is the last generator, so the value of the x component of each pair changes most frequently.

Dependent Generators Later generators can depend on the variables that are introduced by earlier generators. [(x,y) x <- [1..3], y <- [x..3]] The list [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] of all pairs of numbers (x,y) such that x and y are elements of the list [1..3] and y x. Using a dependant generator we can define the library function that concatenates a list of lists: concat :: [[a]] -> [a] concat xss = [x xs <- xss, x <- xs] > concat [[1,2,3],[4,5],[6]] [1,2,3,4,5,6] 26

Guards List comprehensions can use guards to restrict the values produced by earlier generators. [x x <- [1..10], even x] list all numbers x s.t. x is an element of the list [1..10] and x is even Example: Using a guard we can define a function that maps a positive integer to its list of factors: factors :: Int -> [Int] factors n = [x x <- [1..n], n `mod` x == 0] > factors 15 [1,3,5,15] 27

A positive integer is prime if its only factors are 1 and itself. Hence, using factors we can define a function that decides if a number is prime: prime :: Int -> Bool prime n = factors n == [1,n] > prime 15 False > prime 7 True Using a guard we can now define a function that returns the list of all primes up to a given limit: primes :: Int -> [Int] primes n = [x x <- [2..n], prime x] > primes 40 [2,3,5,7,11,13,17,19,23,29,31,37] 28

The Zip Function A useful library function is zip, which maps two lists to a list of pairs of their corresponding elements. zip :: [a] -> [b] -> [(a,b)] > zip [ a, b, c ] [1,2,3,4] [( a,1),( b,2),( c,3)] Using zip we can define a function that returns the list of all positions of a value in a list: positions :: Eq a => a -> [a] -> [Int] positions x xs = [i (x,i) <- zip xs [0..n], x == x ] where n = length xs - 1 > positions 0 [1,0,0,1,0,1,1,0] [1,2,4,7] 29

Using zip we can define a function that returns the list of all pairs of adjacent elements from a list: pairs :: [a] -> [(a,a)] pairs xs = zip xs (tail xs) > pairs [1,2,3,4] [(1,2),(2,3),(3,4)] Using pairs we can define a function that decides if the elements in a list are sorted: sorted :: Ord a => [a] -> Bool sorted xs = and [x y (x,y) <- pairs xs] > sorted [1,2,3,4] True > sorted [1,3,2,4] False 30

Exercises (1) A triple (x,y,z) of positive integers is called pythagorean if x 2 + y 2 = z 2. Using a list comprehension, define a function pyths :: Int -> [(Int,Int,Int)] that maps an integer n to all such triples with components in [1..n]. For example: > pyths 5 [(3,4,5),(4,3,5)] pyths n = [(x,y,z) x<-[1..n], y<-[1..n], z<-[1..n], x^2+y^2==z^2] 31

32 (2) A positive integer is perfect if it equals the sum of all of its factors, excluding the number itself. Using a list comprehension, define a function perfects :: Int [Int] that returns the list of all perfect numbers up to a given limit. For example: > perfects 500 [6,28,496]

33 (3) The scalar product of two lists of integers xs and ys of length n is given by the sum of the products of the corresponding integers: n-1 i = 0 (xs i * ys i ) Using a list comprehension, define a function that returns the scalar product of two lists. scalarproduct :: [Int] -> [Int] -> Int scalarproduct xs ys = sum[x*y (x,y) <- zip xs ys]