Operators, Functions and Modules1 Pattern Matching & Recursion.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Functional Programming Lecture 10 - type checking.
Chapter 3 DATA: TYPES, CLASSES, AND OBJECTS. Chapter 3 Data Abstraction Abstract data types allow you to work with data without concern for how the data.
Operators, Functions and Modules1 Operators and Functions.
Comp 205: Comparative Programming Languages Functional Programming Languages: Haskell Lecture notes, exercises, etc., can be found at:
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.
CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Definitions. name :: Type answer :: Int name = expression answer = Definitions associate a name with a value of a certain type is of type greater.
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.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Java Data Types. Primitive Data Types Java has 8 primitive data types: – char: used to store a single character eg. G – boolean: used to store true or.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Overview of the Haskell 98 Programming Language
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
1 Comments Allow prose or commentary to be included in program Importance Programs are read far more often than they are written Programs need to be understood.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Guards1. 2 Let’s test this function. Main> maxi Here is a trace of the function: n m maxi 3 2 Guards or conditions are used to express various cases.
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.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Lesson 4 String Manipulation. Lesson 4 In many applications you will need to do some kind of manipulation or parsing of strings, whether you are Attempting.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 2 Variables.
Conditional Expressions
Chapter 2 Basic Computation
Types CSCE 314 Spring 2016.
Haskell Chapter 2.
Tokens in C Keywords Identifiers Constants
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
A lightening tour in 45 minutes
Multiple variables can be created in one declaration
Haskell.
CSE 3302 Programming Languages
Type Conversion, Constants, and the String Object
Week 3: Basic Operations
IDENTIFIERS CSC 111.
Type Conversion, Constants, and the String Object
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Lectures on Numerical Methods
Type & Typeclass Syntax in function
Rocky K. C. Chang September 18, 2018 (Based on Zelle and Dierbach)
PROGRAMMING IN HASKELL
Chapter 3 Mathematical Functions, Strings, and Objects
Fundamentals of Functional Programming
CHAPTER 3: String And Numeric Data In Python
PROGRAMMING IN HASKELL
Functions and patterns
Computer Science 312 Making choices Tail Recursion
Chapter 2 Variables.
PROGRAMMING IN HASKELL
Presentation transcript:

Operators, Functions and Modules1 Pattern Matching & Recursion

Operators, Functions and Modules2 add2 0 b = b add2 a 0 = a add2 a b = a + b A pattern can be A literal 0 ‘a’ True False A variable any argument value will match this Wild card “_” any argument value will match this A tuple pattern (p1, p2, …, pn) matches a tuple with matching values A constructor Here is a simple use of patterns in defining a function add2 :: Int -> Int -> Int

Operators, Functions and Modules3 A problem The following table shows the weekly sales in a company, Week Sales We want to know that given a week n, What is the total sales from week 0 to week n What is the maximum weekly sales from week 0 to week n Function to calculate total sales given a particular week: We will first represent the table of weekly data, sales :: Int -> Int sales 0 = 15 sales 1 = 5 sales 2 = 7 sales 3 = 18 sales 4 = 7 sales 5 = 0 sales 6 = 5

Operators, Functions and Modules4 totalSales :: Int -> Int totalSales n | n = = 0 = sales 0 | otherwise = totalSales (n-1) + sales n We have used recursion in the definition of our functions. This type of recursion is called primitive recursion. The first clause is called the base case and the second clause is called the recursive case. totalSales 4 = totalSales 3 + sales 4 = (totalSales 2 + sales 3) + sales 4 = ((totalSales 1 + sales 2) + sales 3 )+ sales 4 = (((totalSales 0 + sales 1) + sales 2) + sales 3 )+ sales 4 = ((((sales 0 + sales 1) + sales 2) + sales 3 ) + sales 4 = = 57 Definition of totalSales (using guards):

Operators, Functions and Modules5 maxSales 4 = maxi (sales 4) maxSales 3 = maxi 7 (maxi (sales 3) maxSales 2) = maxi 7 (maxi 18 (maxi (sales 2) maxSales 1)) = maxi 7 (maxi 18 (maxi 7 (maxi (sales 1) maxSales 0))) = maxi 7 (maxi 18 (maxi 7 (maxi 5 sales 0))) = maxi 7 (maxi 18 (maxi 7 (maxi 5 15))) = maxi 7 (maxi 18 (maxi 7 15)) = maxi 7 (maxi 18 15) = maxi 7 18 = 18 Function to calculate maximum sales(using guards): maxSales :: Int -> Int maxSales n | n = = 0 = sales 0 | otherwise = maxi (sales n) maxSales (n-1)

Operators, Functions and Modules6 Pattern matching could have been used for defining these functions. Pattern matching may be used when we have a number of equations. Each equation can become a pattern. Let’s now define totalSales and maxSales using patterns. totalSales 0 = sales 0 totalSales n = totalSales (n-1) + sales n maxSales 0 = sales 0 maxSales n = maxi (sales n) (maxSales (n-1)) The underscore “_” (known as don’t care) can be used as a pattern and we use it when we do not care about the value it matches with. isZero :: Int -> Bool isZero 0 = True isZero _ = False Prelude> isZero ‘A’

Operators, Functions and Modules7 More Types

Operators, Functions and Modules8 The ASCII code of the characters can also be used for representing them. For instance, ‘\65’ is equivalent to ‘A’. Character Type Char is a Haskell built-in type. Characters are put inside single quotes. ‘a’ to ‘z’, ‘A’ to ‘Z’, ‘0’ to ‘9’ Some characters are represented using a backslash “\” before them. Examples are: tab ‘\t’, newline ‘\n’, backslash ‘\\’ single quote ‘\’’, double quote ‘\”’ ASCII codes 65 to 90 represent A-Z ASCII codes 97 to 122 represent a-z ASCII codes 48 to 57 represent 0-9

Operators, Functions and Modules9 Prelude> ord ‘r’ 114 Prelude> ‘\114’ r Prelude> chr (114) r Here is a function for converting a lower case letter to capital. offset :: Int offset = ord ‘A’ – ord ‘a’ toCapital :: Char -> Char toCapital ch = chr (ord ch + offset) Here, we did not have to define offset. We could have simply said: toCapital ch = chr (ord ch + (ord ‘A’ – ‘ord ‘a’)) It is however good practice to define offset as ewe have. There are two useful built in conversion functions. chr :: Int -> Char ord :: Char -> Int

Operators, Functions and Modules10 Other functions toLowr:: Char -> Char toLowr ch = chr (ord ch - offset) isDigit :: Char -> Bool isDigit ch = (‘0’ <= ch) && (ch <= ‘9’) isChar :: Char -> Bool isChar ch = not (isDigit ch)

Operators, Functions and Modules11 The operator ++ used above is the concatenation operator. Prelude>putStr “Massey University” Massey University Prelude> putStr “\99u\116” cut Prelude>putStr “oranges\napples\npears” Strings: A string is a special list consisting of characters. Type String = [Char] Here are some strings: “Haskell is a functional programming language.” ”\72el\108o\t world” “Haskell “ ++ “ programming” oranges apples pears

Operators, Functions and Modules12 Floating Point Numbers Type Float is used for calculations involving floating point numbers. Examples of floating point numbers: Type Float is not used very much. Floating point arithmetic is not very precise in Haskell because of the limited space allowed for the internal representation of floating point numbers. A type like Double may be used for more precision.

Operators, Functions and Modules13 Float -> Float -> Float +, *, -, /, ** (example: x ** y ) Float -> Float cos, sin, tan, abs, sqrt (square root) Float -> Int -> Float ^ (example: x^n) Float -> Int ceiling, floor, round, truncate Integer -> Float fromInteger Float pi (the constant pi) An example: sin (pi/2) * pi Some built-in floating point operations:

Operators, Functions and Modules14 Using Integer and Float answer :: Integer answer=42 Main> answer ERROR - Unresolved overloading *** Type : Fractional Int => Int *** Expression : answer Prelude> answer + truncate Prelude> fromInteger answer Prelude> floor Prelude> ceiling Prelude> round Prelude> truncate 2.8 2

Operators, Functions and Modules15 Function to compute average of weekly sales meanSales :: Integer -> Float meanSales n = fromInteger (totalSales n) / fromInteger (n+1)