CSc 372 Comparative Programming Languages

Similar documents
CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. 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

CS 320: Concepts of Programming Languages

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

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

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

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

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Lecture 2: List algorithms using recursion and list comprehensions

Lecture 19: Functions, Types and Data Structures in Haskell

CSc 520. Principles of Programming Languages 11: Haskell Basics

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

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

02157 Functional Programming Lecture 2: Functions, Basic Types and Tuples

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Shell CSCE 314 TAMU. Haskell Functions

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

CS 457/557: Functional Languages

Haskell through HUGS THE BASICS

Logical Methods in... using Haskell Getting Started

Haskell Scripts. Yan Huang

Programming Languages Fall 2013

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

More fun with recursion

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

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

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

A general introduction to Functional Programming using Haskell

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

An introduction introduction to functional functional programming programming using usin Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell

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

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

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

List Functions, and Higher-Order Functions

Haskell Overview III (3A) Young Won Lim 10/4/16

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

Intro to Haskell Notes: Part 5

CS 320: Concepts of Programming Languages

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

Shell CSCE 314 TAMU. Functions continued

Standard prelude. Appendix A. A.1 Classes

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

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

CSc 520 Principles of Programming Languages. 26 : Control Structures Introduction

SMURF Language Reference Manual Serial MUsic Represented as Functions

CS3110 Spring 2017 Lecture 10 a Module for Rational Numbers

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

Principles of Programming Languages

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes

Programming Paradigms

CS 11 Haskell track: lecture 1

Programming Languages

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

Course year Typeclasses and their instances

INTRODUCTION TO FUNCTIONAL PROGRAMMING

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

Programming Languages

Functional Programming in Haskell Part I : Basics

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen

Overloading, Type Classes, and Algebraic Datatypes

CSc 520 Principles of Programming Languages

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

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

CS 360: Programming Languages Lecture 12: More Haskell

CSE 341 Section 5. Winter 2018

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number?

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

Functional Programming TDA 452, DIT 142

LECTURE 16. Functional Programming

An introduction to functional programming. July 23, 2010

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

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

SML A F unctional Functional Language Language Lecture 19

Programming Languages

02157 Functional Programming Tagged values and Higher-order list functions

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions

Thinking Induc,vely. COS 326 David Walker Princeton University

Extended Static Checking for Haskell (ESC/Haskell)

Week 5 Tutorial Structural Induction

CS 320: Concepts of Programming Languages

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

Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh

Introduction to OCaml

Haskell-Tutorial. Damir Medak Gerhard Navratil. Institute for Geoinformation Technical University Vienna. February 2003

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

Lists. Michael P. Fourman. February 2, 2010

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CS 209 Functional Programming

02157 Functional Programming. Michael R. Ha. Tagged values and Higher-order list functions. Michael R. Hansen

Transcription:

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 [1]

Functions over Lists [2]

Breaking Lists ctake ctake n xs (from the standard prelude) takes a number n and a list of characters, and returns the first n elements of the list. Examples: ctake 3 [ a, b, c, d, e ] [ a, b, c ] ctake 3 [ a, b ] [ a, b ] Haskell: ctake :: Int -> [Char] -> [Char] ctake 0 = [ ] ctake [ ] = [ ] ctake (n+1) (x:xs) = x : ctake n xs [3]

Don t Get Confused! What do the two arrows in the signature of ctake mean? ctake :: Int -> [Char] -> [Char] This is something called Currying, which we will talk about in the next lecture. For now, think two arrows in the function signature means the function takes two arguments. This is a lie, but I ll be more truthful later. ctake takes an Int and a list of Chars as input, and returns a list of Chars. [4]

Breaking Lists drop drop n xs (from the standard prelude) takes a number n and a list, and returns the remaining elements when the first n have been removed. Examples: drop 3 [ a, b, c, d, e ] [ d, e ] drop 3 [ a, b ] [ ] drop 3 [1,2,3,4,5] [4,5] Haskell: drop :: Int -> [a] -> [a] drop 0 xs = xs drop [ ] = [ ] drop (n+1) (x:xs) = drop n xs [5]

Don t Get Confused (take 2)! What do the two [a]s in the signature of drop mean? drop :: Int -> [a] -> [a] drop is what s called a Polymorphic Function, which we will talk more about soon. The idea is that a is a type variable, that can take on any type we want. So, drop can work on lists of Ints, lists of Chars, etc. [6]

List Element Selection The operator!! in the standard prelude returns an element of a list. Lists are indexed starting at 0. Examples: [2,5,8,3,9,5,7]!!3 3 [2,5]!!3 ERROR [[1],[2,3],[4]]!!1!!0 2 We can write our own list element selector function: elmt :: [Int] -> Int -> Int elmt (x: ) 0 = x elmt ( :xs) (n+1) = elmt xs n [7]

Don t Get Confused (take 3)! We can actually define elmt to be an operator, just like in the standard prelude: infixl 9!! (!!) :: [a] -> Int -> a (x: )!! 0 = x ( :xs)!! (n+1) = xs!! n infixl 9 declares!! to be a left-associative operator with precedence 9. We ll talk more about this later... [8]

The zip Function zip takes two lists xs and ys and returns a list zs of pairs drawn from xs and ys. xs and ys are combined like the two parts of a zipper. Extra elements from different length lists are discarded. Examples: zip [1,2] [ a, b ] [(1, a ),(2, b )] zip [1,2,3] [ a, b ] [(1, a ),(2, b )] Haskell: zip :: [a] -> [b] -> [(a,b)] zip (x:xs) (y:ys) = (x,y) : zip xs ys zip = [ ] [9]

The remdups Function Define a function to remove duplicate adjacent elements from a list: remdups [1] [1] remdups [1,2,1] [1,2,1] remdups [1,2,1,1,2] [1,2,2] remdups [1,1,1,2] [1,2,1] We have to consider three cases: 1. The first two elements of the list are identical. Remove one of them, then remove duplicates from the rest of the list. 2. The first two elements are different. Keep them and remove duplicates from the rest of the list. 3. There are fewer that two elements in the list. Keep them. [10]

The remdups Function... Algorithm in English: Case 1: Let the first two elements of the list be x and y. Let x==y. Example: L==[1,1,2,3], x==y==1. Discard x. Recursively remove duplicates from the remaining list L=[1,2,3]. Case 2: The first two elements of the list (x,y) are different (x/=y). Example: L==[1,2,2,3], x==1, y==2. Append x onto the result of removing duplicates from the list L =[2,2,3] from which x has been removed. Case 3: The list has 0 or 1 element. Return it. [11]

The remdups Function... Simulation: emdups [1,2,2] 1:(remdups 2:[2]) case 2,x=1,y=2,xs=[2] 1:(remdups [2,2]) 1:(remdups 2:[ ]) case 1,x=y=2,xs=[ ] 1:(remdups [2]) 1:[2] case 3,xs=[2] [1,2] [12]

The remdups Function... Algorithm in Haskell: remdups :: [Int] -> [Int] remdups x:y:xs = if x == y then remdups y:xs case 1 else x : remdups y:xs case 2 remdups xs = xs case 3 case 1: First two elements identical. case 2: First two elements different. case 3: Less than 2 elements left. x:y:xs matches any list with 2 or more elements. [13]

Haskell Guards Remember the guard syntax in Haskell: fun name fun args guard 1 = expr 1 guard 2 = expr 2 otherwise = expr n This is equivalent to: fun name fun args if guard 1 then expr 1 else if guard 2 then expr 2 else if else expr n [14]

Haskell Guards... Many functions become more succinct using guards: fact with guards: fact :: Int -> Int fact n n==0 = 1 otherwise = n * fact (n-1) remdups with guards: remdups :: Eq [a] => [a] -> [a] remdups (x:y:xs) x==y = remdups (y:xs) x /= y = x : remdups (y:xs) remdups xs = xs [15]

Don t Get Confused (take 4)! What does the Eq [a] => mean in the signature of remdups? remdups :: Eq [a] => [a] -> [a] Again, remdups is defined as a polymorphic function, and should therefore work on lists of any element type. However, it will only work on elements for which == is defined, because, without an equality test available we can t test if two adjacent elements are the same! Eq [a] => means that remdups can only be applied to elements that can be compared with ==. We ll talk more about this later.... [16]

The append Function We want to define a function that appends two lists together: append [1,2] [3,4] [1,2,3,4] append [ ] [1,2] [1,2] Only use cons (":") and recursion. Remember that cons creates a new list from an element x and a list xs, such that x is the first element and xs the last elements of the list: 5 : [1,2] [5,1,2] [17]

The append Function... Algorithm for append xs ys: 1. Take xs apart and use cons to put the elements together to make a new list. 2. Again use cons to make ys the tail of this new list. [18]

The append Function... Simulation: append [1,2,3] [4,5] 1: (append [2,3] [4,5]) 1: (2: (append [3] [4,5])) 1: (2: (3: (append [ ] [4,5]))) 1: (2: (3: [4,5])) 1: (2: [3,4,5]) 1: [2,3,4,5] [1,2,3,4,5] [19]

The append Function... Note how we take the first argument apart when going into the recursion, and how it is put together when returning back up. Notice also that the second argument to append is never traversed. It is simply tacked on (using cons) to the end of the new list when the bottom of the recursion has been reached. [20]

The append Function... Algorithm in Haskell: append :: [a] -> [a] -> [a] append [ ] xs = xs append (x:xs) ys = x : append xs ys ++ as append: It is more convenient to define append as an infix operator. ++ is predefined in the standard prelude. infixr 5 ++ (++) :: [a] -> [a] -> [a] [ ]++xs = xs (x:xs) ++ ys = x : (xs ++ ys) [21]

Local Definitions [22]

The where Clause In some languages we can nest declarations, i.e. declarations can be made local to a particular procedure: function P ( ) : function X ( ) :... begin X( ) end. The local function X can only be accessed from within P. This is an important way to break a complicated routine into manageable chunks. We also hide the definition of X from routines other than P. Haskell has a where-clause that works much the same way as a local function or variable. [23]

The where Clause... The where-clause follows after a function body: fun name fun args = <fun body> where decl 1 decl 2 decl n A declaration decl i is like any global function definition. Note that a constant declaration id = expr is allowed since it is seen as a constant 0-argument function. [24]

The where Clause... deriv f x = (f(x+dx) - f x)/dx where dx = 0.0001 sqrt x = newton f x where f y = yˆ2 - x Note that the scope (area of visibility) of a where-clause is the entire right-hand side of the function definition. [25]

The where Clause... g :: Int -> Int g n (n mod 3) == x = x (n mod 3) == y = y (n mod 3) == z = z where x = 0 y = 1 z = 2 [26]

The let Clause An other, less flexible way, of introducing a local definition, is the let-clause. The syntax of a let-clause: let <local definitions> in <expression> Note that the scope of the let-clause is only one expression, whereas the where clause can span over several. [27]

The let Clause... f :: [Int] -> [Int] f [ ] = [ ] f xs = let square a = a * a one = 1 (y:ys) = xs in (square y + one) : f ys [28]

The let Clause... f [1,2] (square 1 + one) : f [2] 2 : f [2] 2 : ((square 2 + one) : f [])) 2 : (5 : f []) 2 : (5 : []) 2 : [5] [2,5] [29]

Rational Arithmetic Package [30]

Rational Arithmetic Build a package implementing rational arithmetic. Arithmetic Laws: a b + c ad + bc = d bd a b c d = ac bd a b c d = ad bc bd a b /c d = ad bc 5 4 + 6 7 = 5 7 + 4 6 4 7 5 4 6 7 = 5 6 4 7 = 15 14 = 59 28 [31]

Rational Arithmetic... There is more than one way to represent the same rational number: 1 7 = 1 7 = 3 21 = 168 1176 We would like to represent each rational number a b in the simplest way, called the normal form, such that a 168 and b are relatively prime. Hence, 1176 would always be represented as 7 1. Two numbers a and b are relatively prime if a and b have no common divisor. 9 and 16 are relatively prime, but 9 and 15 aren t (they both have the common divisor 3). 0 is always represented by 0 1. [32]

Rational Arithmetic... We represent a rational number as a tuple of the numerator and the denominator: type Rat = (Int, Int) We normalize a Rat by dividing the numerator and denominator by their greatest common divisor. normrat :: Rat -> Rat normrat (,0) = error("invalid!\n") normrat (0, ) = (0,1) normrat (x,y) = (a div d,b div d) where a = (signum y) * x d = abs y b = gcd a b normrat (-168,1176) (-1,7) [33]

Rational Arithmetic... The signum Function: signum x (from the standard prelude) returns -1 if x is negative, 0 if x is 0, and 1 if x is positive. signum :: (Num a, Ord a) => a -> Int signum n n == 0 = 0 n > 0 = 1 n < 0 = -1 The gcd Function: gcd :: Int -> Int -> Int gcd x y = gcd (abs x) (abs y) where gcd x 0 = x gcd x y = gcd y (rem x y) gcd 78 42 6 [34]

Rational Arithmetic... Arithmetic: negrat :: Rat -> Rat negrat (a,b) = normrat (-a,b) addrat,subrat,mulrat,divrat ::Rat -> Rat -> Rat addrat (a,b) (c,d) = normrat (a*d + c*b, b*d) subrat (a,b) (c,d) = normrat (a*d - c*b, b*d) mulrat (a,b) (c,d) = normrat (a*c, b*d) divrat (a,b) (c,d) = normrat (a*d, b*c) Examples: > addrat (4,5) (5,6) (49,30) [35]

Rational Arithmetic... Relational Comparison: eqrat :: Rat -> Rat -> Bool eqrat (a,0) (c,d) = err eqrat (a,b) (c,0) = err eqrat (a,b) (c,d) = (a*d == b*c) where err = error "Invalid!" Examples: > eqrat (4, 0) (4, 1) Invalid! > eqrat (4, 0) (4, 0) Invalid! > eqrat (4, 5) (4, 5) True > eqrat (4, 5) (4, 6) False [36]

Exercises [37]

Homework Define a function split xs that takes alist of pairs, makes two lists, one from the first elements of the pair and the other from the second pair elements, and returns the two lists as a pair. Examples: split [(1,"a"),(2,"b"),(3,"c")] ([1,2,3],["a","b","c"]) split [(1,True),(2,False),(3,False)] ([1,2,3],[True,False,False]) [38]

Homework We model vectors as triples of floating point numbers: type Vector = (Float, Float, Float) Define functions add v, scale v, dot v (dot product), and cross v (cross product) according to the definitions below: (a 1,a 2,a 3 ) + (b 1,b 2,b 3 ) = (a 1 + b 1,a 2 + b 2,a 3 + b 3 ) k(a 1,a 2,a 3 ) = (ka 1,ka 2,ka 3 ) (a 1,a 2,a 3 ) (b 1,b 2,b 3 ) = a 1 b 1 + a 2 b 2 + a 3 b 3 (a 1,a 2,a 3 ) (b 1,b 2,b 3 ) = (a 2 b 3 b 2 a 3,a 3 b 1 a 1 b 2,a 1 b 2 a 2 b 1 ) [39]

Homework... 1. Now model 3 3 matrices as triples of Vector. 2. Define a function scale m that scales a matrix m by a float s, i.e. multiplies all elements by s. 3. Define a function add m that adds two matrices a and b together to form a new matrix c, i.e. c i,j = a i,j + b i,j. 4. Define a function transpose m m that turns the rows of a matrix m into columns, and vice versa, i.e. t i,j = m j,i. [40]