Outline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists

Size: px
Start display at page:

Download "Outline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists"

Transcription

1 Arrays and Lists

2 Outline Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists

3 Collections We've seen tuples to store multiple objects together, but the tuple syntax of._# is awkward and doesn't scale. Collection types solve this problem in Scala. The 2 basic collection types are Arrays and Lists The Array and the List are referred as sequence. That means that they store a number of different values in a specific order that you can get to the elements in them by an integer index. These differ in the way they are laid out in memory (and thus their efficiency for different problems), but many of the same methods are used for both; and many problems are solvable by both.

4 Arrays

5 Array Contiguous, Ordered, Rigidly structured Syntax: val arr = Array(12, 0, 31, 14) arr(0) //12 arr(2) //31 Arrays are mutable: arr(1) = 27 //arr now equals [12, 27, 31, 14] ++ joins arrays together

6 Lists

7 Lists Non-contiguous, Ordered, Flexible Syntax: val lst = List(12, 0, 31, 14) lst(0) //12 lst(2) //31 Lists are immutable: lst(1) = 27 //ERROR But new, longer/shorter lists are easily created: val newlst = 1 :: lst //[1,12,0,31,14] :: is the cons operator ::: joins lists together

8

9 Exercise: array operations val a = new Array[Int](5) val b = new Array[Boolean](10) val c = Array(1,2,3,4) a(2) b(5) c(0) a.length b.length c.length val d = a ++ c d.length

10 Exercise: List operations val lstofchars = List('a','b','c') val lstofints1 = List(1,2,3,4) val lstofints2 = List(5,6,7,8) lstofchars(1) // b lstofints1(0) // 1 lstofints2(0) // 5 lstofchars.length // 3 val onemore = 42 :: lstofints1 // List(42,1,2,3,4) val combined = lstofints1 ::: lstofints2 val conslist = 20 :: 21 :: 22 :: 23 :: Nil conslist.length // 4 conslist(3) // 23

11 Array vs List

12 Parametric Types List[Int] Array[Boolean]

13 Functions using arrays Arrays are objects, and can be arguments/parameters to functions, as well as return values Recursion can be useful to create functions/procedures that operate on arrays, typically by passing an "index" value as an additional argument to the function

14 fillarray fillarray - initialize each element of an array to be the value of a series def fillarray(arr:array[int],index:int):unit = { if(index<arr.length) { arr(index)=readint() fillarray(arr,index+1) } } This function does not return a result. The fact that Arrays are mutable means that we can pass in an array and have the function mutate the contents. As a result, nothing needs to be returned.

15 operateonarray operateonarray - combine array elements together using a specified function def operateonarray(arr:array[int],index:int,func:(int,int)=>int):int={ if(index<arr.length-1) { func(arr(index),operateonarray(arr,index+1,func))} else { arr(arr.length-1)} }

16 Functions on Lists Lists are objects, and can be arguments to functions, parameter of functions, as well as return values Recursion can be useful to create functions/procedures that operate on lists; unlike Arrays, recursion over lists typically involves two list methods:.head -- returns the first element in a list; for a List[A] this return value is of the type A.tail -- returns the rest of the list after the 1st element; for a List[A] this return value is also a List[A]

17 inputlist - make a list from user inputs def inputlist():list[int] = { val in = readline if (in== quit ) Nil else in.toint :: inputlist() }

18 operateonlist - combine list elements together using a specified function def operateonlist(lst:list[int],func:(int,int)=>int):int = { if(lst.tail==nil) lst.head else func(lst.head,operateonlist(lst.tail,func)) }

19 Standard Methods for Array/List/Collections isempty reverse slice(from:int, until:int) splitat(ind:int) take(n:int) sum, min, max contains(elem:any) mkstring and many more

20 Higher-order methods Creating Array/List fill(size)(pass_by_name_variable) tabulate(size)(f: Int=>B) When you already have an array/list map(f:(a)=>b) filter(p:(a)=>boolean) foreach(f:(a)=>unit) forall(p(a)=>boolean) reduceleft(f:(a,a)=>a) reduceright(f:(a,a)=>a) and many more

21 Fill val a = Array.fill(5)(1) //currying and pass_by_name variable val b = Array.fill(10)("Hello") val c = List.fill(5)(math.random) val d = Array.fill(3)(readInt) var i=1 val j = List.fill(5){ i*=2; i } //List(2, 4, 8, 16, 32)

22 Tabulate The tabulate method creates a new list or array filling each element with its index that has a function that you supply applied to it. val e = Array.tabulate(3)((x:Int)=>x) val f = Array.tabulate(12)((x:Int)=>x.toString*2) val g = Array.tabulate(4)((x:Int)=>(x>2)) val h = List.tabulate(5)((_:Int)*2) val i = List.tabulate(100)((z:Int)=>z.toString)

23 Map The map method takes a function that operates on an element and results in something. It produces a new collection that contains the results of applying that function to all the contents of the original collection. val j = List(1, 2, 3, 4) j.map(_ + 1) j.map(_ * 2) j.map(i => i * i)

24 Filter The filter method takes a function that will operate on an element and result in a Boolean. Produces a new collection that contains only the elements for which the function is true. val k = List(1, 2, 3, 4) k.filter(_ < 3) k.filter(x => x>=4 && x<=7) k.filter(_ % 2 == 0)

25 Foreach and forall foreach(f:(a)=>unit) takes a function that operates on an element and applies it to all elements in the collection. The result type is Unit. This method is called only for the side effects. forall(p:(a)=>boolean) takes a function that will operate on an element and result in a Boolean. Its value is true if the function is true for all elements of the collection. val l = List(1, 2, 3, 4) l.foreach(println) l.forall(_ > 0) //true l.forall(_ > 4) //false

26 Reduce val m = List(7,4,6,3,9,1) m.reduceleft(_ + _) // Means m.reduceleft(_ * _) // Means 7*4*6*3*9*1 m.reduceleft(_ - _) // Means m.reduceright(_ - _) // Means 7-(4-(6-(3-(9-1))))

27 Aliasing val a = Array(1,2,3,4) val b = a b(1) = 42 //This changed both a & b //because b is an "alias" of a

28 Cloning val a = Array(1,2,3,4) val b = a b(1) = 42 //This changed both a & b //because b is an "alias" of a val c = a.clone c(1) = 27 //This changes only c

29 Exercise Suppose a is an Array[String]; write statement that prints elements of a, one on each line val a = Array( 3, 5, 6 ) convert elements of the array to integers, then compute sum a.map( ).reduceleft( )

30 One-dimensional arrays Two ways to create 1-d arrays. //New, empty arrays. Automatically initialized to ZERO. syntax: new Array[T](#) val x = new Array[Int](10)//ZERO means 0. val y = new Array[String](5)// ZERO means null. //New and Initialized arrays val z = Array.fill(10)( ) val w = Array.tabulate(10)(x=>3*x*x)

31 Multi-dimensional Arrays Several syntax options: Array(Array(1,2), Array(3,4)) //New, empty arrays val a = new Array[Array[Int]](4) for(i <- 0 until 4) a(i) = new Array[Int](10) val b = Array.ofDim[Int](2,3,4) //Initialized arrays val c = Array.fill(2,4)( ) val d = Array.tabulate(2,3)((x,y)=>f(x,y))

List are immutable Lists have recursive structure Lists are homogeneous

List are immutable Lists have recursive structure Lists are homogeneous WORKING WITH LISTS val fruit = List("apples", "oranges", "pears") val nums: List[Int] = List(1, 2, 3, 4) val diag3 = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty = List() List are immutable

More information

CS205: Scalable Software Systems

CS205: Scalable Software Systems CS205: Scalable Software Systems Lecture 4 September 14, 2016 Lecture 4 CS205: Scalable Software Systems September 14, 2016 1 / 16 Quick Recap Things covered so far Problem solving by recursive decomposition

More information

Collections and Combinatorial Search

Collections and Combinatorial Search Streams Collections and Combinatorial Search We ve seen a number of immutable collections that provide powerful operations, in particular for combinatorial search. For instance, to find the second prime

More information

CS205: Scalable Software Systems

CS205: Scalable Software Systems CS205: Scalable Software Systems Lecture 3 September 5, 2016 Lecture 3 CS205: Scalable Software Systems September 5, 2016 1 / 19 Table of contents 1 Quick Recap 2 Type of recursive solutions 3 Translating

More information

Linked lists and the List class

Linked lists and the List class Linked lists and the List class Cheong 1 Linked lists So far, the only container object we used was the array. An array is a single object that contains references to other objects, possibly many of them.

More information

Recursion & Iteration

Recursion & Iteration Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion

More information

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review File processing Files are opened with the open() command. We can open files for reading or writing. The open() command takes two arguments, the file name

More information

Figure 1: A complete binary tree.

Figure 1: A complete binary tree. The Binary Heap A binary heap is a data structure that implements the abstract data type priority queue. That is, a binary heap stores a set of elements with a total order (that means that every two elements

More information

CompSci 220. Programming Methodology 12: Functional Data Structures

CompSci 220. Programming Methodology 12: Functional Data Structures CompSci 220 Programming Methodology 12: Functional Data Structures A Polymorphic Higher- Order Function def findfirst[a](as: Array[A], p: A => Boolean): Int = { def loop(n: Int): Int = if (n >= as.length)

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 13 February 12, 2018 Mutable State & Abstract Stack Machine Chapters 14 &15 Homework 4 Announcements due on February 20. Out this morning Midterm results

More information

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

Documentation for LISP in BASIC

Documentation for LISP in BASIC Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Sorting The sorting problem is defined as follows: Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays: College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 11 Arrays: A. Write a code snippet to define the following arrays: 1. An int array named nums of size 10.

More information

Exercise 1: Graph coloring (10 points)

Exercise 1: Graph coloring (10 points) Exercise 1: Graph coloring (10 points) Graph coloring is the problem of assigning colors to vertices in a non-directed graph, so that no two adjacent nodes have the same color. In other words, if two vertices

More information

Ruby: Objects and Dynamic Types

Ruby: Objects and Dynamic Types Ruby: Objects and Dynamic Types Computer Science and Engineering College of Engineering The Ohio State University Lecture 5 Primitive vs Reference Types Recall Java type dichotomy: Primitive: int, float,

More information

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12 CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can

More information

CS 2340 Objects and Design - Scala

CS 2340 Objects and Design - Scala CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes

More information

Programming Principles

Programming Principles Programming Principles Final Exam Friday, December 21st 2012 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write your

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

SCALA ARRAYS. Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.

SCALA ARRAYS. Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9. http://www.tutorialspoint.com/scala/scala_arrays.htm SCALA ARRAYS Copyright tutorialspoint.com Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of

More information

Appendix A. Scala Tools. A.1 Command Line

Appendix A. Scala Tools. A.1 Command Line Appendix A Scala Tools A.1 Command Line............................................................................ 625 A.2 sbt.........................................................................................

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

This page intentionally left blank

This page intentionally left blank This page intentionally left blank Arrays and References 391 Since an indexed variable of the array a is also a variable of type double, just like n, the following is equally legal: mymethod(a[3]); There

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Functional programming

Functional programming Functional programming Functional programming In functional programming, functions are the core building blocks In pure functional programming, functions are like mathematical functions Mathematical functions

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

You ve encountered other ways of signalling errors. For example, if you lookup an unbound key in a hashtable, Java (and Scala) produce nulls:

You ve encountered other ways of signalling errors. For example, if you lookup an unbound key in a hashtable, Java (and Scala) produce nulls: Lecture 5 1 Required Reading Read Chapters 16 and 17 of Programming in Scala. 2 Partial Functions and Signalling Errors Many functions are not defined on all inputs. For example, if you re reading input

More information

Parallel Programming

Parallel Programming Parallel Programming Midterm Exam Wednesday, April 27, 2016 Your points are precious, don t let them go to waste! Your Time All points are not equal. Note that we do not think that all exercises have the

More information

All the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)

All the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple) Weekly exercises in INF3110 week 41 6-10.10.2008 Exercise 1 Exercise 6.1 in Mitchell's book a) fun a(x,y) = x+2*y; val a = fn : int * int -> int All the operations used in the expression are over integers.

More information

Extended Example: Discrete Event Simulation

Extended Example: Discrete Event Simulation Extended Example: Discrete Event Simulation 1 Introduction This chapter shows by way of an extended example how objects and higher-order functions can be combined in interesting ways. The task is to design

More information

n n Official Scala website n Scala API n

n   n Official Scala website n Scala API n n Quiz 8 Announcements n Rainbow grades: HW1-8, Quiz1-6, Exam1-2 n Still grading: HW9, Quiz 7 Scala n HW10 due today n HW11 out today, due Friday Fall 18 CSCI 4430, A Milanova 1 Today s Lecture Outline

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy Announcements CSCI 334: Principles of Programming Languages Lecture 16: Intro to Scala HW7 sent out as promised. See course webpage. Instructor: Dan Barowy Announcements No class on Tuesday, April 17.

More information

Practically Functional. Daniel Spiewak

Practically Functional. Daniel Spiewak Practically Functional Daniel Spiewak whoami Author of Scala for Java Refugees and other articles on Scala and FP Former editor Javalobby / EclipseZone Engaged in academic research involving Scala DSLs

More information

Datatype declarations

Datatype declarations Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS

More information

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page. MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

More information

1 of 5 5/11/2006 12:10 AM CS 61A Spring 2006 Midterm 2 solutions 1. Box and pointer. Note: Please draw actual boxes, as in the book and the lectures, not XX and X/ as in these ASCII-art solutions. Also,

More information

Week 8: Functions and States

Week 8: Functions and States Week 8: Functions and States Until now, our programs have been side-eect free. Therefore, the concept of time wasn't important. For all programs that terminate, any sequence of actions would have given

More information

L3 Programming September 19, OCaml Cheatsheet

L3 Programming September 19, OCaml Cheatsheet OCaml Cheatsheet Note: this document comes from a previous course (by Sylvain Schimdt). The explanations of the OCaml syntax in this sheet are by no means intended to be complete or even sufficient; check

More information

What the optimizer does to your code

What the optimizer does to your code 1 / 12 Miguel Garcia http://lamp.epfl.ch/~magarcia LAMP, EPFL 2012-04-18 2 / 12 Outline Things the optimizer is good at Example Pros and Cons Early inlining Parallelizing an optimization phase Further

More information

Outline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants

Outline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants CSE 142 Outline for Today Conditional statements if Boolean expressions Comparisons (=,!=, ==) Boolean operators (and, or, not - &&,,!) Class invariants Conditional Statements & Boolean Expressions

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages CMSC330 Fall 2017 OCaml Data Types CMSC330 Fall 2017 1 OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists

More information

Parallel Operations on Collections. Parallel Programming in Scala Viktor Kuncak

Parallel Operations on Collections. Parallel Programming in Scala Viktor Kuncak Parallel Operations on Collections Parallel Programming in Scala Viktor Kuncak Parallelism and collections Parallel processing of collections is important one the main applications of parallelism today

More information

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline Bibliography Analyse et Conception Formelle Lesson 5 Crash Course on Scala Simply Scala. Onlinetutorial: http://www.simply.com/fr http://www.simply.com/ Programming in Scala, M. Odersky, L. Spoon, B. Venners.

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

More information

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1 A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1 A First Look At Java Didactic Module 13 Programming Languages - EEL670 1 Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Python Review IPRE

Python Review IPRE Python Review Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

...something useful to do with the JVM.

...something useful to do with the JVM. Scala Finally... ...something useful to do with the JVM. Image source: http://www.tripadvisor.com/locationphotos-g187789-lazio.html Young Developed in 2003 by Martin Odersky at EPFL Martin also brought

More information

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017 Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

More information

Swift. Introducing swift. Thomas Woodfin

Swift. Introducing swift. Thomas Woodfin Swift Introducing swift Thomas Woodfin Content Swift benefits Programming language Development Guidelines Swift benefits What is Swift Benefits What is Swift New programming language for ios and OS X Development

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Stateful Objects. can I withdraw 100 CHF? may vary over the course of the lifetime of the account.

Stateful Objects. can I withdraw 100 CHF? may vary over the course of the lifetime of the account. Functions and State Functions and State Until now, our programs have been side-effect free. Therefore, the concept of time wasn t important. For all programs that terminate, any sequence of actions would

More information

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341 Spring 2017, Final Examination June 8, 2017 CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

INF121: Functional Algorithmic and Programming

INF121: Functional Algorithmic and Programming INF121: Functional Algorithmic and Programming Lecture 6: Polymorphism, Higher-order, and Currying Academic Year 2011-2012 In the previous episodes of INF 121 Basic Types: Booleans, Integers, Floats, Chars,

More information

List of lectures. Lecture content. Imperative Programming. TDDA69 Data and Program Structure Imperative Programming and Data Structures

List of lectures. Lecture content. Imperative Programming. TDDA69 Data and Program Structure Imperative Programming and Data Structures List of lectures TDDA69 Data and Program Structure Imperative Programming and Data Structures Cyrille Berger 1Introduction and Functional Programming 2Imperative Programming and Data Structures 3Parsing

More information

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

A quick introduction to SML

A quick introduction to SML A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

More information

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 11 Polymorphism The functional iterator interface we have defined last lecture is nice, but it is not very general.

More information

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330, Fall 2013, Practice Problem 3 Solutions CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change

More information

Logic - CM0845 Introduction to Haskell

Logic - CM0845 Introduction to Haskell Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester

More information

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

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

CSCI 3155: Homework Assignment 3

CSCI 3155: Homework Assignment 3 CSCI 3155: Homework Assignment 3 Spring 2012: Due Monday, February 27, 2012 Like last time, find a partner. You will work on this assignment in pairs. However, note that each student needs to submit a

More information

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University ACL2 www.cs.utexas.edu/~moore/acl2 ACL2 is a programming language, logic, and theorem prover/checker

More information

Classical Themes of Computer Science

Classical Themes of Computer Science Functional Programming (Part 1/2) Bernhard K. Aichernig Institute for Software Technology Graz University of Technology Austria Winter Term 2017/18 Version: November 22, 2017 1/49 Agenda I Functional Programming?

More information

CSE 341 Section Handout #6 Cheat Sheet

CSE 341 Section Handout #6 Cheat Sheet Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

More information

(Not Quite) Minijava

(Not Quite) Minijava (Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

Exercises on ML. Programming Languages. Chanseok Oh

Exercises on ML. Programming Languages. Chanseok Oh Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max

More information

Lecture 2. 1 Immutability. 2 Case Classes

Lecture 2. 1 Immutability. 2 Case Classes Lecture 2 1 Immutability Consider the function incrlist in fig. 3.1, which increments all numbers in a list. We want to emphasize that incrlist produces a new list and leaves the original list unchanged.

More information

21 Subtyping and Parameterized Types

21 Subtyping and Parameterized Types Object-Oriented Design Lecture 21 CS 3500 Spring 2011 (Pucella) Friday, Apr 1, 2011 21 Subtyping and Parameterized Types Given a parameterized type Foo[T], suppose we know that A B (A is a subtype of B),

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th

CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th Name: CAS ID (e.g., abc01234@pomona.edu): I encourage you to collaborate. collaborations below. Please record your Each question is worth

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Functional Programming

Functional Programming Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

More information

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

More information

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures Today s topics Types of objects and procedures Procedural abstractions Capturing patterns across procedures Higher Order Procedures Types (+ 5 1) ==> 15 (+ "hi 5) ;The object "hi", passed as the first

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

More information

Dynamic Data Types - Recursive Records

Dynamic Data Types - Recursive Records Dynamic Data Types - Recursive Records Example: class List { int hd; List tl ;} J.Carette (McMaster) CS 2S03 1 / 19 Dynamic Data Types - Recursive Records Example: class List { int hd; List tl ;} Note:

More information