Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i <- 2 to 5) println(i + " squared.

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

Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Lists 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.
Computer Science 1620 Loops.
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
Visual Basic: An Object Oriented Approach 3 – Making Objects Work.
Getting Functional. 2 What is Functional Programming (FP)? In FP, Functions are first-class objects. That is, they are values, just like other objects.
Chapter 8 Arrays and Strings
Programming in Scala Chapters 2 & 3. Two “Hello World” programs package hello object HelloWorld1 extends Application { println("Hello, world 1!") } package.
CS0007: Introduction to Computer Programming Introduction to Arrays.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
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.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
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”
Introduction to Python
Chapter 5: Control Structures II (Repetition)
Lists in Python.
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
Chapter 8 Arrays and Strings
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
“In mathematics and computer programming, Index notation is used to specify the elements of an array of numbers”
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
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.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Data Structures & Algorithms
RUBY by Ryan Chase.
Cases and Classes and Case Classes And Other Miscellany 16-Dec-15.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
23-Feb-16 Lists. Arrays and Lists Arrays are a fixed length and occupy sequential locations in memory This makes random access (for example, getting the.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Swift. Introduced in 2014 Replaces Objective-C as “recommended development language” “safer, succinct, readable” Emphasizes type safety.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
CS1022 Computer Programming & Principles
Introduction to Computer Science / Procedural – 67130
Compiler Design First Lecture.
Error Handling Summary of the next few pages: Error Handling Cursors.
Lists 20-Sep-18.
Arrays, For loop While loop Do while loop
Functions As Objects.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data Structures – 1D Lists
T. Jumana Abu Shmais – AOU - Riyadh
String and Lists Dr. José M. Reyes Álamo.
Loops.
(more) Python.
Programming Languages Dan Grossman 2013
Presentation transcript:

Sequences and for loops

Simple for loops A for loop is used to do something with every element of a sequence scala> for (i <- 2 to 5) println(i + " squared is " + i * i) 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 scala> for (i <- "supercalifragilisticexpealedoceous") print(i + "-") s-u-p-e-r-c-a-l-i-f-r-a-g-i-l-i-s-t-i-c-e-x-p-e-a-l-e-d-o-c-e-o-u-s- scala> var sum = 0; for (i <- 1 to 100) sum = sum + i sum: Int = 5050 So, what is a “sequence”? 2

Ranges are sequences scala> 1 to 5 res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5) scala> 1 until 5 res1: scala.collection.immutable.Range = Range(1, 2, 3, 4) scala> Range(1, 5) res2: scala.collection.immutable.Range = Range(1, 2, 3, 4) scala> 1 to 5 by 2 res3: scala.collection.immutable.Range = Range(1, 3, 5) scala> 1 until 5 by 2 res4: scala.collection.immutable.Range = Range(1, 3) scala> Range(1, 5, 2) res5: scala.collection.immutable.Range = Range(1, 3) scala> for (i <- Range(1, 5)) print(i)

Arrays are sequences scala> Array(2, 3, 5, 7, 11, 13) res0: Array[Int] = Array(2, 3, 5, 7, 11, 13) scala> Array("one", "two", "three") res1: Array[String] = Array(one, two, three) scala> new Array[Int](8) res2: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0) scala> new Array[String](4) res3: Array[String] = Array(null, null, null, null) scala> res3(1) = "one" scala> res3(0) = "zero" scala> res3 res6: Array[String] = Array(zero, one, null, null) 4

Vectors are sequences scala> Vector(2, 3, 5, 7, 11, 13) res0: scala.collection.immutable.Vector[Int] = Vector(2, 3, 5, 7, 11, 13) scala> Vector("one", "two", "three") res1: scala.collection.immutable.Vector[String] = Vector(one, two, three) How are Arrays and Vectors different? Arrays are mutable: You can change their contents You saw this on the previous slide Vectors are immutable: You cannot change them How are Arrays and Vectors similar? You can index into them (starting from zero), to find a value scala> res1(0) res12: String = one 5

Lists are sequences scala> List(3, 8, 5) res0: List[Int] = List(3, 8, 5) scala> List("hot", "dog") res1: List[String] = List(hot, dog) scala> List(1, 2, 3.75) res2: List[Double] = List(1.0, 2.0, 3.75) scala> List('a', "String", 3, 5.0, true) res3: List[Any] = List(a, String, 3, 5.0, true) scala> for (i <- res3) print(i) aString35.0true 6

Strings are (sort of) sequences scala> for (ch <- "abc123") print((ch + 1).toChar) bcd234 scala> "abc123".toCharArray res13: Array[Char] = Array(a, b, c, 1, 2, 3) Strings can be indexed to choose a character scala> var abc123 = "abc123" abc123: String = abc123 scala> abc123(5) res2: Char = 3 Strings are immutable scala> abc123(5) = 'x' :9: error: value update is not a member of String abc123(5) = 'x' But you can create new strings scala> val abc123x = abc123 + 'x' abc123x: String = abc123x 7

Immutability and val Variables have values A variable declared with val cannot be assigned a different value This is a property of the variable, not the value But if the value is something that “has contents,” you can change the contents scala> val x = Array(1, 2, 3) x: Array[Int] = Array(1, 2, 3) scala> x(1) = 999 scala> x res1: Array[Int] = Array(1, 999, 3) Immutability is a property of values, not of variables scala> var v = Vector(1, 2, 3) v: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3) scala> v(1) = 999 :9: error: value update is not a member of scala.collection.immutable.Vector[Int] v(1) = 999 ^ 8

References 9 val a = 5 5 a val b = ab 5 val x = Array(1, 2, 3) x123 val y = x y x(0) = 9 9

for loops with filters So far we’ve only been using the simplest form of a for The first part, variable <- sequence, is a generator For example, n <- 1 to 10 generates the values 1, 2, 3, …, 10 and puts each one in turn into the variable n You can put a filter (a condition) after the generator scala> for (i <- 1 to 8 if i != 5) print(i + " ") You can use more than one condition scala> for (i <- 1 to 24 if 24 % i == 0) print(i + " ") It’s more readable (hence, better style) to put the conditions on separate lines scala> for (i <- 1 to 24 | if 24 % i == 0) print(i + " ")

for loops with generators You can have more than one generator: scala> for (i <- 1 to 3; j <- 100 to 300 by 50) print((i + j) + " ") The semicolon is required, even if the generators are on separate lines scala> for (i <- 1 to 3; | j <- 1 to 3) print((i * j) + " ") You have to start with a generator, but after that you can have generators and filters in any reasonable order 11

for loop with variables You can introduce variables scala> for (i <- 1 to 10; j = 3 * i) print(j + " ") Variables introduced in a for loop are automatically val You get a new, “different” val each time through the loop Again, the semicolon is required You have to start with a generator, but after that you can have generators, filters, and new variables in any reasonable order scala> val n = 30 n: Int = 30 scala> for (i <- 1 until n; | sum = i * (i + 1) | if sum == n) { | println(n + " is pronic") | } 30 is pronic 12

Sequence comprehensions for ( variable <- sequence ) expression evaluates the expression for each value in the sequence The value of the for expression is just unit—not very useful You use a for loop for what it does (adds up values, prints something, etc.), not for its value for ( variable <- sequence ) yield expression evaluates the expression for each value in the sequence The value of the for-yield expression is a sequence of the values computed by the expression This is a for comprehension or sequence comprehension You use a comprehension for its value Example: scala> for (n <- 1 to 10) yield n * n res6: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100) 13

Many types of sequences In the previous example, Scala said the type was an IndexedSeq[Int], but printed it as a Vector scala> for (n <- 1 to 10) yield n * n res6: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100) Since many operations apply to almost all sequences, you usually don’t have to worry about what kind of sequence you get If you start with a particular kind of sequence, for-yield will (usually) return the same kind of sequence scala> for (n <- Array(1, 3, 5, 7)) yield n * n res11: Array[Int] = Array(1, 9, 25, 49) scala> for (n <- List(1, 3, 5, 7)) yield n * n res12: List[Int] = List(1, 9, 25, 49) scala> for (n <- Range(1, 10, 2)) yield n * n res13: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 9, 25, 49, 81) Notice that this result cannot be expressed as a Range 14

Example comprehensions scala> val s = "CIT 591 is my favorite class!" s: String = CIT 591 is my favorite class! scala> for (ch <- s if ch.isLetter) yield ch res14: String = CITismyfavoriteclass scala> val s = "bookkeeper" s: String = bookkeeper scala> for (i <- 0 until s.length – 1 if s(i) == s(i + 1)) yield s(i) res17: scala.collection.immutable.IndexedSeq[Char] = Vector(o, k, e) 15

A longer example “rot13” is a simple “secret code,” in which each letter of the alphabet is replaced by one 13 locations away from it scala> def rot13(message: String) = | for (c <- message) yield { | if (c.isLetter) { | val cRotated = (c + 13).toChar | if (cRotated.isLetter) cRotated | else (c - 13).toChar | } | else c | } rot13: (message: String)String scala> rot13("Scala is a great language!") res20: String = Fpnyn vf n terng ynathntr! scala> rot13(rot13("Scala is a great language!")) res21: String = Scala is a great language! 16

The End 17 Programmer’s Drinking Song (sung to the tune of “100 Bottles of Beer”) 99 little bugs in the code, 99 bugs in the code, Fix one bug, compile it again, 101 little bugs in the code. 101 little bugs in the code.... (Repeat until BUGS = 0) –Anonymous