Methods. Why methods? A method gives a name to something that you want to do, so you don’t have to think about how to do it, you just do it The name should.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
Java Programming Strings Chapter 7.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
What have we learned so far… Preprocessor directives Introduction to C++ Variable Declaration Display Messages on Screen Get Information from User Performed.
Introduction to C Programming
Lists Introduction to Computing Science and Programming I.
Debugging Introduction to Computing Science and Programming I.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Access to Names Namespaces, Scopes, Access privileges.
16-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
10-Sep-15 Classes. Classes and objects Scala is an Object-Oriented (O-O), functional language Object-Oriented (O-O) means it’s built around “objects”
Testing Michael Ernst CSE 140 University of Washington.
The Scala API Application Programmer’s Interface.
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Writing Scala Programs. Command Line There are three common operating systems: Windows (various flavors; I recommend Windows 7) UNIX or Linux (basically.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
More about Classes and Objects. Names Scala has three kinds of names for variables and methods Names composed of letters, underscores, and dollar signs.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
COMPUTER PROGRAMMING. A Typical C++ Environment Phases of C++ Programs: 1- Edit 2- Preprocess 3- Compile 4- Link 5- Load 6- Execute Loader Primary Memory.
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
Procedural programming in Java Methods, parameters and return values.
Basic Program Construction
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Cases and Classes and Case Classes And Other Miscellany 16-Dec-15.
Scalatest. 2 Test-Driven Development (TDD) TDD is a technique in which you write the tests before you write the code you want to test This seems backward,
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Java-02 Basic Concepts Review concepts and examine how java handles them.
Expressions and Data Types Professor Robin Burke.
Today’s Agenda ML Development Workflow –Emacs –Using use –The REPL More ML –Shadowing Variables –Debugging Tips –Boolean Operations –Comparison Operations.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Instant Scala.
Chapter 7 User-Defined Methods.
Types CSCE 314 Spring 2016.
CSE 341 Section 1 (9/28) With thanks to Dan Grossman, et. al. from previous versions of these slides.
Data types and variables
Strings Part 1 Taken from notes by Dr. Neil Moore
CSE 341: Programming Languages Section 1
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company. 1
Lesson 2: Building Blocks of Programming
CS 106A, Lecture 9 Problem-Solving with Strings
Functions As Objects.
T. Jumana Abu Shmais – AOU - Riyadh
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
CISC124 Labs start this week in JEFF 155. Fall 2018
Classes, Objects and Methods
Just Enough Java 17-May-19.
Introduction to C Programming
Presentation transcript:

Methods

Why methods? A method gives a name to something that you want to do, so you don’t have to think about how to do it, you just do it The name should be descriptive and memorable Since a method is an action, it’s name is usually a verb Methods that do more than one thing are harder to name and harder to use Typical names: toChar, sort, sqrt, startsWith Example usages: scala> ('a' + 1).toChar res4: Char = b scala> "anteater".startsWith("ant") res7: Boolean = true 2

Two kinds of methods Classes describe objects (more about this later!) String is a class, and " anteater " is an object of that class Int is a class, and 'a' + 1 is an object of that class When we ask an object to compute something for us, we use dot notation ('a' + 1).toChar "anteater".startsWith("ant") We’ll learn more about classes later, but for now we will study “standalone” methods You have already met a couple of these methods val name = readLine("What is your name?" ) println("Hello, " + name) 3

Method syntax Here is the syntax for a method definition: def methodName ( parameters ): returnType = expression The parameters are a list of name : type pairs Scala can usually figure out the types of values for itself scala> val v = 3.6 v: Double = 3.6 Scala cannot determine parameter types, so you must specify them explicity Scala can usually determine the returnType, but sometimes you have to specify it Here is the syntax for a method call (or invocation): methodName ( arguments ) The arguments (sometimes called actual parameters) may be any expressions You do not specify the types of arguments, they just have to have the types expected by the method You can use a method anywhere a value of that type is required 4

Example: Palindromes A palindrome is a word or phrase that reads the same way backwards and forwards, for example, radar String objects have a reverse method, so we can define an isPalindrome method as follows: scala> def isPalindrome(s: String) = s == s.reverse isPalindrome: (s: String)Boolean and use it like this: scala> isPalindrome("radar") res16: Boolean = true We had to specify the type of the parameter s We always have to specify the type of each parameter We didn’t have to specify the return type (but we can if we want to) def isPalindrome(s: String): String = s == s.reverse Scala can usually figure out the return type 5

Palindromes II There is nothing wrong with writing very short methods (such as isPalindrome ) if it makes your program easier to understand In this case, I think just writing s == s.reverse is just as easy So let’s add some complexity! “Anna” is normally considered to be a palindrome, regardless of capitalization scala> isPalindrome("Anna") res18: Boolean = false Strings have a method toLowerCase to replace capital letters with their lowercase equivalents scala> def isPalindrome(s: String) = | s.toLowerCase == s.reverse.toLowerCase isPalindrome: (s: String)Boolean scala> isPalindrome("Anna") res20: Boolean = true Note: The vertical bar, |, is Scala’s prompt to tell us our expression isn’t finished 6

A little bit of string manipulation We can use a for loop to step through the characters of a string one at a time scala> for (ch <- "Anna") { | println(ch) | } A n n a We can use the + operator to add characters to a string scala> "abc" + 'd' res23: String = abcd We’ll use these in our next definition of isPalindrome 7

Removing non-letters from a string scala> var result = "" // empty string result: String = "" scala> var message = "One if by land, two if by sea" message: String = One if by land, two if by sea scala> for (ch result res25: String = Oneifbylandtwoifbysea 8

Palindromes III scala> :paste // Entering paste mode (ctrl-D to finish) def isPalindrome(s: String) = { var string1 = "" for (ch isPalindrome("Madam, I'm Adam!") res27: Boolean = true 9

Compound expressions The code for isPalindrome looked like this: def isPalindrome(s: String) = { // several lines of code omitted… string1.toLowerCase == string1.reverse.toLowerCase } The body of the method (the expression following the = sign) is a compound expression A compound expression consists of braces, {}, enclosing zero or more expressions If the braces are empty (zero expressions), the value is the unit, denoted () The value of a compound expression is the value of the last expression evaluated in it Hence, the value of the above method is the value of the expression string1.toLowerCase == string1.reverse.toLowerCase 10

Palindromes IV Just to neaten things up without changing how the program works (this is called refactoring), here’s one more version: def deleteNonLetters(s: String) = { var result = "" for (ch <- s) { if (ch.isLetter) { result = result + ch } } result } def isPalindrome(s: String) = { val temp = deleteNonLetters(s).toLowerCase temp == temp.reverse } 11

How I did it I wrote the earliest, simple versions in the REPL Once the method got long enough that I started making lots of mistakes, I wrote it as a script Here’s where I made most of my mistakes: Forgetting to lowercase both the original and the reversed string Forgetting to discard non-letters from both the original and the reversed string Simple typing errors (“typos”) Also I forgot that, in a script, the deleteNonLetters method must appear before it is used in isPalindrome This careful ordering of methods isn’t required in a program 12

Testing Of course, we have to test the method as we go along scala> isPalindrome("A man, a plan, a canal--Panama!") res5: Boolean = true scala> isPalindrome("Anna") res6: Boolean = true scala> isPalindrome("") res7: Boolean = true And don’t forget: scala> isPalindrome("success") res8: Boolean = false 13

AtomicTest in the REPL If you have installed the code supplied with the textbook, you have a very simple test framework Just enter this line: import com.atomicscala.AtomicTest._ Then you can use tests of the form: method-call is expected-result For example: scala> isPalindrome("Anna") is true true scala> isPalindrome("Anne") is false false scala> isPalindrome("Anne") is true false [Error] expected: true 14

AtomicTest in a script Put this line at the very beginning of your script: import com.atomicscala.AtomicTest._ Then put lines like this at the end of your script: isPalindrome("Anna") is true isPalindrome("A man, a plan, a canal--Panama!") is true isPalindrome("Anne") is false Here’s what is looks like in the REPL: scala> :load Palindrome.scala Loading Palindrome.scala... import com.atomicscala.AtomicTest._ deleteNonLetters: (s: String)String isPalindrome: (s: String)Boolean true true false 15

The End 16