0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
Chapter 9 More About Higher-Order Functions. Currying Recall the function: simple n a b = n * (a+b) Note that: simple n a b is really (((simple n) a)
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive 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,
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.
0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Chapter 9: Functional Programming in a Typed Language.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
COP4020 Programming Languages Functional Programming Prof. Xin Yuan.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
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.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
Chapter SevenModern Programming Languages1 A Second Look At ML.
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. 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)
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Lecture 14: Advanced Topic: Functional Programming
Functional Programming
Conditional Expressions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Functions and patterns
ML Again ( Chapter 7) Patterns Local variable definitions
A lightening tour in 45 minutes
Haskell Chapter 4.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Haskell.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
Functions and patterns
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Functions and patterns
PROGRAMMING IN HASKELL
Lambda Expressions Cases
PROGRAMMING IN HASKELL
Presentation transcript:

0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions

1 Conditional Expressions As in most programming languages, functions can be defined using conditional expressions. abs :: Int  Int abs n = if n  0 then n else -n abs takes an integer n and returns n if it is non-negative and -n otherwise.

2 Conditional expressions can be nested: signum :: Int  Int signum n = if n < 0 then -1 else if n == 0 then 0 else 1 zIn Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals. Note:

3 Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations. abs n | n  0 = n | otherwise = -n As previously, but using guarded equations. This is preferred. Try it. Note the parentheses around (-5). Hugs> abs (-5) where abs n | n >= 0 = n | otherwise = -n 5

4 Guarded equations can be used to make definitions involving multiple conditions easier to read: zThe catch all condition otherwise is defined in the prelude by otherwise = True. Note: signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1

5 Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool  Bool not False = True not True = False not maps False to True, and True to False. not x | x == False = True | x == True = False not x | x == False = True | otherwise = False

6 Functions can often 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 True && True = True _ && _ = False can be defined more compactly by _ is “don’t care.” and x y | x == True && y == True = True | otherwise = False

7 True && b = b False && _ = False However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: zThe underscore symbol _ is a wildcard pattern that matches any argument value. Note:

8 zPatterns may not repeat variables. For example, the following definition gives an error: b && b = b _ && _ = False zPatterns are matched in order. For example, the following definition always returns False: _ && _ = False True && True = True This is too bad. Would like to be able to use this to mean that the arguments are equal. But you can’t.

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:[]))).

10 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.

11 Note: x:xs patterns must be parenthesized, because application has priority over (:). For example, the following definition gives an error: x:xs patterns only match non-empty lists: > head [] Error head x:_ = x Hugs> hd [1, 2, 3] where hd x:_ = x ERROR - Syntax error in declaration (unexpected symbol ":") Hugs> hd [1, 2, 3] where hd (x:_) = x 1

12 Integer Patterns pred :: Int  Int pred (n+1) = n As in mathematics, functions on integers can be defined using n+k patterns, where n is an integer variable and k>0 is an integer constant. pred maps any positive integer to its predecessor.

13 Note: zn+k patterns only match integers  k. > pred 0 Error Hugs> pred 5 4 Hugs> pred 0 Hugs> pred (-1) -2 In the prelude pred is defined as subtract 1. Hugs> prd 5 where prd (n+1) = n 4 Hugs> prd 0 where prd (n+1) = n Program error: pattern match failure: v Hugs> prd’ 5 where prd’ (n+2) = n 3

14 zn+k patterns must be parenthesized, because application has priority over +. For example, the following definition gives an error: pred n+1 = n

15 Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. x  x+x the nameless function that takes a number x and returns the result x+x. More real functional programming stuff!

16 zThe symbol is the Greek letter lambda, and is typed at the keyboard as a backslash \. zIn mathematics, nameless functions are usually denoted using the  symbol, as in x  x+x. zIn Haskell, the use of the symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based. Note:

17 Why Are Lambda's Useful? Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: add x y = x+y add = x  ( y  x+y) means add is the function of x ( x) that returns (  ) a function of y ( y) that returns (  ) x+y.

18 const :: a  b  a const x _ = x is more naturally defined by const :: a  (b  a) const x = _  x Lambda expressions are also useful when defining functions that return functions as results. For example:

19 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] Lambda expressions can be used to avoid naming functions that are only referenced once. For example: The most common use. Hugs> odds 5 where odds n = map (\x -> x*2 + 1) [0..n-1] [1,3,5,7,9]

20 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

21 This convention also allows one of the arguments of the operator to be included in the parentheses. For example: > (1+) 2 3 > (+2) 1 3 In general, if  is an operator then functions of the form (  ), (x  ) and (  y) are called sections. Hugs> f 3 where f = (1+) 4 This defines f as (1+) without mentioning f’s argument. Equivalent to Hugs> f 3 where f x = (1+) x 4

22 Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: - successor function - reciprocation function - doubling function - halving function (1+) (*2) (/2) (1/) Cute, but I don’t use this much.

23 Exercises 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)a conditional expression; (b)guarded equations; (c)pattern matching. Hint: the library function null :: [a]  Bool can be used to test if a list is empty. (1)

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