Names and Functions. Chapter 2

Similar documents
Case by Case. Chapter 3

COP 4516: Math for Programming Contest Notes

Learning Log Title: CHAPTER 3: ARITHMETIC PROPERTIES. Date: Lesson: Chapter 3: Arithmetic Properties

Conditionals !

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS 310 Advanced Data Structures and Algorithms

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

Arithmetic and Bitwise Operations on Binary Data

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Introduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD

Lecture 7: General Loops (Chapter 7)

Course Learning Outcomes for Unit I. Reading Assignment. Unit Lesson. UNIT I STUDY GUIDE Number Theory and the Real Number System

Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952. Computing for Biomedical Scientists

Text Input and Conditionals

Technical Section. Lab 4 while loops and for loops. A. while Loops or for loops

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

APCS Semester #1 Final Exam Practice Problems

Types, Expressions, and States

EXAMPLE 1. Change each of the following fractions into decimals.

If Control Construct

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08013 INFORMATICS 1 - FUNCTIONAL PROGRAMMING

CS302: Self Check Quiz 2

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Properties and Definitions

Chapter 1 An Introduction to Computer Science. INVITATION TO Computer Science 1

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Adding and Subtracting Integers

Working with recursion

Math 171 Proficiency Packet on Integers

1 5 Integer Operations

Lecture 3: Recursion; Structural Induction

The type of all data used in a C++ program must be specified

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

Algorithm Design: GCD

2. MACHINE REPRESENTATION OF TYPICAL ARITHMETIC DATA FORMATS (NATURAL AND INTEGER NUMBERS).

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

Project 3: RPN Calculator

Integers and Absolute Value. Unit 1 Lesson 5

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

CS 3410 Ch 7 Recursion

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Problem Set CVO 103, Spring 2018

Exam Datastrukturer. DIT960 / DIT961, VT-18 Göteborgs Universitet, CSE

CSCE 110: Programming I

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

What is a Fraction? Fractions. One Way To Remember Numerator = North / 16. Example. What Fraction is Shaded? 9/16/16. Fraction = Part of a Whole

Section 1.2 Fractions

Basic data types. Building blocks of computation

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself. Gaddis:

1007 Imperative Programming Part II

UNIT 1: INTEGERS Definition Absolute Value of an integer How to compare integers

The following expression causes a divide by zero error:

CSc 372 Comparative Programming Languages

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Introduction to Computer Science

Decimal Binary Conversion Decimal Binary Place Value = 13 (Base 10) becomes = 1101 (Base 2).

MORE OCAML Algorithms, Methods & Diversions

Lecture 11: Recursion (hard)

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

Answers to Questions. Chapter 1 (Starting Off)

Algorithms 4. Odd or even Algorithm 5. Greatest among three numbers Algorithm 6. Simple Calculator Algorithm

UCT Algorithm Circle: Number Theory

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Final Examination: Topics and Sample Problems

If a b or a c, then a bc If a b and b c, then a c Every positive integer n > 1 can be written uniquely as n = p 1 k1 p 2 k2 p 3 k3 p 4 k4 p s

Math library for PIC18 processors version 0.05

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Introduction and Overview

15 212: Principles of Programming. Some Notes on Induction

Module 05: Types of recursion

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Computational Physics - Fortran February 1997

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

First Haskell Exercises

Integers. Integer Definition. Slide 1 / 237. Slide 2 / 237. Slide 3 / 237. Integer Unit Topics

Recursion & Performance. Recursion. Recursion. Recursion. Where Recursion Shines. Breaking a Problem Down

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday

Fundamental of Programming (C)

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Euclid's Algorithm. MA/CSSE 473 Day 06. Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm

Spring Semester 13, Dr. Punch. Exam #1 (2/14), form 1 A

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

DeMorgan's Theorem. George Self. 1 Introduction

CS421 Spring 2014 Midterm 1

15 150: Principles of Functional Programming. Exceptions

Pre-Algebra Notes Unit One: Variables, Expressions, and Integers

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

The Beauty and Joy of Computing 1 Lab Exercise 4: Starting a simple math tutor program and more interaction

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

Arithmetic Processing

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

in this web service Cambridge University Press

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final

Transcription:

Chapter 2 Names and Functions So far we have built only tiny toy programs. To build bigger ones, we need to be able to name things so as to refer to them later. We also need to write expressions whose result depends upon one or more other things. Before, if we wished to use a sub-expression twice or more in a single expression, we had to type it multiple times: # 200 * 200 * 200;; Instead, we can define our own name to stand for the result of evaluating an expression, and then use the name as we please: # let x = 200;; val x : int = 200 # x * x * x;; To write this all in a single expression, we can use the let... =... in construct: # let x = 200 in x * x * x;; # let a = 500 in (let b = a * a in a + b);; - : int = 250500 We can also make a function, whose value depends upon some input (we call this input an argument we will be using the word input later in the book to mean something different): 9

10 Chapter 2. Names and Functions # let cube x = x * x * x;; val cube : int -> int = <fun> # cube 200;; We chose cube for the name of the function and x for the name of its argument. When we typed the function in, replied by telling us that its type is int int. This means it is a function which takes an integer as its argument, and, when given that argument, evaluates to an integer. To use the function, we just write its name followed by a suitable argument. In our example, we calculated 200 3 by giving the cube function 200 as its argument. The cube function has type int int, we gave it an integer 200, and so the result is another integer. Thus, the type of the expression cube 200 is int remember that the type of any expression is the type of the thing it will evaluate to, and cube 200 evaluates to 8000000, an integer. In diagram form: int int int {}}{{}}{ cube 200 }{{} int If we try an argument of the wrong type, the program will be rejected: # let cube x = x * x * x;; val cube : int -> int = <fun> # cube false;; Error: This expression has type bool but an expression was expected of type int Here is a function which determines if an integer is negative: # let neg x = if x < 0 then true else false;; val neg : int -> bool = <fun> # neg (-30);; we add parentheses to distinguish from neg - 30 - : bool = true But, of course, this is equivalent to just writing # let neg x = x < 0;; val neg : int -> bool = <fun> # neg (-30);; - : bool = true because x < 0 will evaluate to the appropriate boolean value on its own true if x < 0 and false otherwise. Here is another function, this time of type char bool. It determines if a given character is a vowel or not:

Chapter 2. Names and Functions 11 # let isvowel c = c = 'a' c = 'e' c = 'i' c = 'o' c = 'u';; val isvowel : char -> bool = <fun> # isvowel x ;; - : bool = false Notice that we typed the function over two lines. This can be done by pressing the Enter key in between lines. knows that we are finished when we type ;; followed by Enter as usual. Notice also that we pressed space a few times so that the second line appeared a little to the right of the first. This is known as indentation and does not affect the meaning of the program at all it is just for readability. There can be more than one argument to a function. For example, here is a function which checks if two numbers add up to ten: # let addtoten a b = a + b = 10;; val addtoten : int -> int -> bool = <fun> # addtoten 6 4;; - : bool = true The type is int int bool because the arguments are both integers, and the result is a boolean. We use the function in the same way as before, but writing two integers this time, one for each argument the function expects. A recursive function is one which uses itself. Consider calculating the factorial of a given number the factorial of 4 (written 4! in mathematics), for example, is 4 3 2 1. Here is a recursive function to calculate the factorial. Note that it uses itself in its own definition. # let rec factorial a = if a = 1 then 1 else a * factorial (a - 1);; val factorial : int -> int = <fun> # factorial 4;; - : int = 24 We used let rec instead of let to indicate a recursive function. How does the evaluation of factorial 4 proceed? factorial 4 = 4 * factorial 3 = 4 * (3 * factorial 2) = 4 * (3 * (2 * factorial 1)) = 4 * (3 * (2 * 1)) = 4 * (3 * 2) = 4 * 6 = 24

12 Chapter 2. Names and Functions For the first three steps, the else part of the conditional expression is chosen, because the argument a is greater than one. When the argument is equal to one, we do not use factorial again, but just evaluate to one. The expression built up of all the multiplications is then evaluated until a value is reached: this is the result of the whole evaluation. It is sometimes possible for a recursive function never to finish what if we try to evaluate factorial (-1)? factorial (-1) = -1 * factorial (-2) = -1 * (-2 * factorial (-3)) = -1 * (-2 * (-3 * factorial (-4))).. The expression keeps expanding, and the recursion keeps going. Helpfully, tells us what is going on: # let rec factorial a = if a = 1 then 1 else a * factorial (a - 1);; val factorial : int -> int = <fun> # factorial (-1);; Stack overflow during evaluation (looping recursion?). This is an example of an error cannot find by merely looking at the program it can only be detected during evaluation. Later in the book, we will see how to prevent people who are using our functions from making such mistakes. One of the oldest methods for solving a problem (called algorithms) still in common use is Euclid s algorithm for calculating the greatest common divisor of two numbers (that is, given two positive integers a and b, finding the biggest positive integer c such that neither a/c nor b/c have a remainder). Euclid was a Greek mathematician who lived about three centuries before Christ. Euclid s algorithm is simple to write as a function with two arguments: # let rec gcd a b = if b = 0 then a else gcd b (a mod b);; val gcd : int -> int -> int = <fun> # gcd 64000 3546;; - : int = 128 Here is the evaluation: gcd 64000 3456 = gcd 3456 1792 = gcd 1792 1664 = gcd 1664 128 = gcd 128 0 = 128

Chapter 2. Names and Functions 13 Finally, here is a simple function on boolean values. In the previous chapter, we looked at the && and operators which are built in to. The other important boolean operator is the not function, which returns the boolean complement (opposite) of its argument true if the argument is false, and vice versa. This is also built in, but it is easy enough to define ourselves, as a function of type bool bool. # let not x = if x then false else true;; val not : bool -> bool = <fun> # not true;; - : bool = false Almost every program we write will involve functions such as these, and many larger ones too. In fact, languages like are often called functional languages.

14 Chapter 2. Names and Functions Questions 1. Write a function which multiplies a given number by ten. What is its type? 2. Write a function which returns true if both of its arguments are non-zero, and false otherwise. What is the type of your function? 3. Write a recursive function which, given a number n, calculates the sum 1 + 2 + 3 +... + n. What is its type? 4. Write a function power x n which raises x to the power n. Give its type. 5. Write a function isconsonant which, given a lower-case character in the range 'a'... 'z', determines if it is a consonant. 6. What is the result of the expression let x = 1 in let x = 2 in x + x? 7. Can you suggest a way of preventing the non-termination of the factorial function in the case of a zero or negative argument?

So Far 1Integers min_int... -3-2 -1 0 1 2 3... max_int of type int. Booleans true and false of type bool. Characters of type char like 'X' and '!'. Mathematical operators + - * / mod which take two integers and give another. Operators = < <= > >= <> which compare two values and evaluate to either true or false. The conditional if expression1 then expression2 else expression3, where expresssion1 has type bool and expression2 and expression3 have the same type as one another. The boolean operators && and which allow us to build compound boolean expressions. 2Assigning a name to the result of evaluating an expression using the let name = expression construct. Building compound expressions using let name1 = expression1 in let name2 = expression2 in... Functions, introduced by let name argument1 argument2... = expression. These have type α β, α β γ etc. for some types α, β, γ etc. Recursive functions, which are introduced in the same way, but using let rec instead of let.