Some Scala problems for self

Size: px
Start display at page:

Download "Some Scala problems for self"

Transcription

1 Some Scala problems for self May 4, 2012

2 2

3 Chapter 1 Getting Started 1.1 Background The book, Programming in Scala, Second Edition (PINS), is very good, and the best way to learn Scala is probably to read it and write as many programs as possible. There are also some url:s which can be useful, such as: The specification (API) of the standard library it s searchable, and has links to the implementation of the standard classes. Contains guides, tutorials, cheat sheets, specifications and information on language improvement proposals. This web-site is quite new, but is intended to become a onestop resource for information about Scala. Lots of links, and lots of questions and answers. The first seminar, and also this text, is geared towards those without, or with only little prior experience of Scala. The purpose of the seminar was to get you started, and these notes contain some problems which hopefully can help you. All problems marked with (*) have solutions in the appendix, and since there usually are several ways to do things in Scala, the appendix have alternative solutions to many of the problems. Feel free to ask me (Christian) anything, either during the scheduled sessions, or at any other time when I m available. 1.2 Fundamentals The form of a simple program in Scala is: object SimpleApp { def main(args: Array[String]) { //... actual code... or, even simpler: 3

4 4 CHAPTER 1. GETTING STARTED object SimplerApp extends App { //... actual code... We begin with some examples just to get to know the REPL, the compiler, and the simplest possible Scala program. Problem 1.1 ( ) Fire up the Scala REPL, and try to make it show the type of the expression println( hello, world ) What is the value of the expression? Problem 1.2 ( ) Implement the hello, world -program, and run it both as a script and as a compiled program. One of the ideas underlaying Scala is to make things easier and more enjoyable for the programmer, and one of the ways it does this is by removing as much boilerplate as possible. To this end it includes an object called Predef, which adds conveniences such as: Methods to print: print, printf and println these are shortcuts to methods on an object called Console. Methods to read from the keyboard: readline, readint and readdouble these are also shortcuts to methods on Console. Some standard collection classes (more about them later). For someone who has used Java, some of the fundamentals of Scala will be very familiar it has if-statements, while-statements, and for-statements (although Scala s for-statement it s much more powerful than it s Java counterpart). Actually, anything we can do in Java, we can do almost exactly the same way in Scala, albeit somewhat more concisely. Sections 2.1 to 2.5 i PINS covers some of the background needed to solve the following problems: Problem 1.3 ( ) Write a program which reads a temperature in F, and outputs the same temperature in C (see the API-docs for how to read and write the temperatures). C = ( F 32) 5 9. Problem 1.4 ( ) Write a program defining a method sum which uses a while-statement to calculate n. Let the program read a n-value from the keyboard and output the sum. 1.3 All values are objects In many languages we have to differentiate between primitive types and reference types, but in Scala every value is an object. This means that should actually be interpreted as: (1).+(2)

5 1.4. FUNCTIONS ARE VALUES 5 Scala has classes corresponding to the primitive types of Java, so there are classes like Int, Double, Char and Boolean, and we can call methods on our primitive values. This means that we can write: val p = x.round.toint instead of (as we do in Java): int p = (int) Math.round(x); One interesting method on Int-values is to when we write val interval = 1 to 100 we get a NumericRange-object, which is a kind of collection containing the values the values are generated on demand, so we don t have to save 100 values at once. The for-statement allows us to iterate through every value of a collection, so we can print the numbers this way: for (k <- 1 to 100) println(k) A NumericRange has a by-method, so we can write for (x <- 0.0 to 1.0 by 0.1) printf( %.1f: %.4f\n, x, math.exp(x)) Observe that we must use a start value of type Double if we re to use a step value of type Double the expression 0 to 5 gives us a NumericRange[Int], whereas 0.0 to 1.0 gives us a NumericRange[Double]. Another kind of value is the tuple (page 46 in PINS) Scala allows us to create tuples of any arity up to 22, and we can create a tuple t with a String, a Boolean and a Double by just writing: val t = ( hello, true, ) We can get the parts of a tuple either by using underscores: val msg = t._1 val b = t._2 val x = t._3 We can also use pattern matching (much more about that later): val (msg, b, x) = t Here each of the variables msg, b and x is set to the corresponding value of t. 1.4 Functions are values During the seminar we spent some time discussing methods and functions they are also described in various places in chapter 2 and 3 of PINS. Problem 1.5 ( ) Write a method fahr2cels which converts from F to C. Also define a function literal ( anonymous function ) which calculates the same conversion, and save the function in a val (eg. f2c). What is the type of the method/function? Write a method tabulate which prints a temperature conversion table, like:

6 6 CHAPTER 1. GETTING STARTED 50.0: : : : : 21.1 It should take four parameters: A function which converts between different temperature scales. A minimum and a maximum temperature. A temperature increment. Call tabulate, once for each of fahr2cels and f2c. Problem 1.6 ( ) Write a method integrate which calculates a b f(x)dx using a simple Riemann sum. The function should take four parameters: The function to integrate (f R R). Lower and upper limits. The step length this parameter could be given a default value of Use this function to calculate: 0 1 x 2 dx and 1 1 e x2 /2 2π dx. The answers should be (approximately) 0.33 and Hint: Look at the until-method on Double, and the by-method on NumericRange[Double] (they may look like one operator: a until b by c, but really are two methods, called on different objects). 1.5 Scala s collections Some of Scala s collection classes are described in chapter 3, and you can find an abundance of information about them on and It is a good idea to read through some of the documentation and get a feel for what the collection classes can do (it s much more than one might at first expect). Problem 1.7 ( ) Write a program which prints all command line arguments in upper case and it should do it two times, first with a for-statement, then with foreach. Hint: An App has access to an Array named args, which gives the command line parameters.

7 1.5. SCALA S COLLECTIONS 7 Problem 1.8 ( ) Write a function which takes a list of Double:s, and returns their average, the number of values less than the average, and the number of values bigger than the average (efficiency is not an issue here) these values should be returned as a 3-tuple. We may safely assume that the list isn t empty (if it were, there wouldn t be any average anyway). Test the program by calling the function with the numbers given on the command line. Hint: Look closely at what the List-class has to offer. Problem 1.9 ( ) In problem 1.6 we wrote a function which calculated a b f(x)dx using a for-loop now we want to do it using some Seq-methods. Hint: Once again, browse through all the Seq methods using two of them we can turn this method into a one-liner (which isn t necessarily a good thing, but in this case it is convenient). Problem 1.10 ( ) Write a program which counts the number of different words on the command line (you get to decide if it should be case sensitive or case insensitive). Hint: Look at Set, and ways to obtain a Set from a Seq (all Seq-methods can be called on an Array). Problem 1.11 ( ) Write a program which prints the first number n for which the decimal representation of n! contains all decimal digits (ie ). The class BigInt is introduced on page 5 in PINS. Hint: It s probably a good idea to convert the BigInt-values to String:s before checking the digits. Problem 1.12 ( ) Write a program which reads a glossary on the form: venio:comes sub:under nostrum:our and puts it in a Map. The lines are read from a file, where the file name is given on the command line. The program should then repetitiously read words and output their translation (or don t know for words it doesn t know): $ scala Translations glossary input word: nostrum translation: our input word: pulchra translation: don t know input word: $... File input is discussed on page 55 in PINS. Hint: To split the word-pairs, we can use the split-method of java.lang.string, and then we can actually create a Map by using the tomap-method on a sequence of pairs (2-tuples). Problem 1.13 ( ) This problem is admittedly rather contrived, but serves to illustrate the use of Map:s, and also that functions can be stored as values in a map (or any kind of collection). We want to read an integer, and then a string of instructions, where the instructions are coded by the following letters:

8 8 CHAPTER 1. GETTING STARTED d : double the current value (always an integer), h : halve the current value (if the current value is odd, divide by two and truncate to the closest smaller integer), p : increase the current value by 1, and m : decrease the current value by 1. The program should then update the input value according to the instructions, such as in this sample run: $ scala Update 1 ddddm 15 $ scala Update 1 ddmdp The value is 7 To solve the problem, we want a Map[Char,Int=>Int], which maps each of the four letters to the corresponding function.

9 Appendix A Suggested solutions to some problems 1.1 We can find the return type by writing: scala> :type println( hello, world ) Unit So, it turns out println returns Unit-values (of which there aren t that many ). We get the return value by writing: println(println( hello, world )) hello, world () or by saving it into a value: scala> val v = println( hello, world ) hello, world v: Unit = () Here the () on the second output line is that unique value of type Unit. If we asked if v is really (), the REPL would reply: if (v == ()) ok else surprising <console>:9: warning: comparing values of types Unit and Unit using == will always yield true if (v == ()) ok else surprising ^ res0: java.lang.string = ok 1.2 A simple hello, world -program is: object Hello extends App { println( hello, world ) and we run it as a script by: $ scala Hello.scala To compile and run it we write: $ fsc Hello.scala $ scala Hello Using fsc will make subsequent compilations much faster (the first time we run it, the compiler daemon must start up, so then there is no gain of time). 9

10 10 APPENDIX A. SUGGESTED SOLUTIONS TO SOME PROBLEMS 1.3 Predef (which is automatically imported) enables us to write: object Temperatures extends App { print( Degrees Fahrenheit: ) val fahrenheit = readdouble val celsius = 5 * (fahrenheit - 32) / 9 printf( That corresponds to %.1f degrees Celsius\n, celsius) The readline-method, which reads a String, can be called with a prompt so if we use.todouble (see below) we can simplify the input slightly: val fahrenheit = readline( Degrees Fahrenheit: ).todouble 1.4 object NotExactlyGauss extends App { def sum(n: Int) = { var sum = 0 var term = 0 while (term < n) { term += 1 sum += term sum print( Enter n: ) val n = readint println(sum(n)) 1.5 The type of the function is R R, which i Scala-speak is Double => Double. Using a regular for-loop in tabulate, we get something like: object Temperatures extends App { def fahr2cels(degf: Double) = (degf - 32) * 5 / 9 val f2c = (degf: Double) => (degf - 32) * 5 / 9 def tabulate(conv: Double => Double, min: Double, max: Double, step: Double) = for (temp <- min to max by step) printf( %5.1f: %5.1f\n, temp, conv(temp)) tabulate(fahr2cels, 30, 80, 5) tabulate(f2c, 30, 80, 5) Instead of an ordinary for-loop, we can use foreach:

11 11 (min to max by step) foreach { temp => printf( %5.1f: %5.1f\n, temp, conv(temp)) 1.6 We want to step through the x-axis, in small steps (dx), and in every step we calculate the area of a narrow rectangle. Since we don t want the rectangles to pass max (or at least by as little as possible), we step only until, not to the max limit. Using a for-loop and a var we get: object Calculus extends App { def integrate(f: Double => Double, min: Double, max: Double, dx: Double = 1e-3) = { var s = 0.0 for (x <- min until max by dx) { s += f(x) * dx s println(integrate(x => x * x, 0, 1)) println(integrate(x => math.exp(- x * x / 2) / math.sqrt(2 * math.pi), -1, 1)) In problem 1.9 we will see an easier way (a one-liner) to implement integrate. 1.7 object ArgsInUppercase extends App { for (arg <- args) println(arg.touppercase) args.foreach(arg => println(arg.touppercase)) 1.8 object BigAndSmall extends App { def statistics(values: List[Double]): (Double, Int, Int) = { val average = values.sum / values.size (average, values.count(_ < average), values.count(_ > average)) val (avg, less, bigger) = statistics(args.tolist.map(_.todouble)) println( Average: %.2f, less: %d, bigger: %d.format(avg, less, bigger)) 1.9 This time we can simplify integrate into: def integrate(f: Double => Double, min: Double, max: Double, dx: Double = 1e-3) = (min until max by dx).map(f).sum * dx

12 12 APPENDIX A. SUGGESTED SOLUTIONS TO SOME PROBLEMS 1.10 We can use the.toset method on args (it feels almost like cheating, but the method is there because Scala tries to be as helpful as possible). object CountWords extends App { println(args.toset.size) If we want a case insensitive solution, we can first map tolowercase over all words: println(args.map(_.tolowercase).toset.size) If we hadn t noticed the toset-method, we could have used a mutable set: object CountWords extends App { val words = collection.mutable.set[string]() for (word <- args) { words += word println(words.size) or, with foreach: object CountWords extends App { val words = collection.mutable.set[string]() args.foreach(words += _) println(words.size) 1.11 A function to calculate n! is given in the book: def factorial(n: BigInt): BigInt = if (n < 2) 1 else n * factorial(n - 1) There are several ways to check if a BigDecimal contains all digits, either way it seems to be a good idea to first convert it into a String. We can check that each of the digits 0 to 9 occurs: val alldigits = ( 0 to 9 ) def containsalldigits(n: BigInt) = { val digits = n.tostring alldigits.forall(c => digits.contains(c)) We can create a set of all digits in n!, and see if the size of the set is 10: def containsalldigits(n: BigInt) = n.tostring.toset.size == 10 We now need a way to iterate until we find the first n with the given property, and we can do it in many ways. A simple iterative solution is: var k = 0 while (!containsalldigits(factorial(k))) k += 1 println(k)

13 Scala s standard library defines streams, and using them we could first define the positive integers, and then drop them as long as n! doesn t contains all digits we then pick up the first number we find. val positiveints = Stream.from(1) val first = positiveints.dropwhile(n =>!containsalldigits(factorial(n))).head println(first) 1.12 Using the hint we get (but of course we can create a mutable Map, and add to it as we input our words): object Translations extends App { val filename = if (args.size > 0) args(0) else glossary val dictionary = io.source.fromfile(filename)( UTF-8 ).getlines.map(_.split( : )).filter(_.size == 2).map(a => (a(0), a(1))).tomap 13 def translate: Unit = { val word = readline( input word: ) if (word.length > 0) { println( translation: + dictionary.getorelse(word, don t know )) translate translate 1.13 If we declare the type of the Map (it will be a Map[Char,Int=>Int]), we don t have to declare the type of every function in its definition (we will have to use parentheses though, because of precedence rules): object MapOfFunctions extends App { val f = Map[Char, Int => Int] ( d -> (n => n * 2), h -> (n => n / 2), p -> (n => n + 1), m -> (n => n - 1)) We can also use placeholder syntax (ie. an underscore) to define our functions: val f = Map[Char, Int => Int] ( d -> (_ * 2), h -> (_ / 2), p -> (_ + 1), m -> (_ - 1)) To use this map for evaluating the sequence of instructions, given the initial number, we have a choice we could either write imperatively, or functionally. We begin with an imperative solution:

14 14 APPENDIX A. SUGGESTED SOLUTIONS TO SOME PROBLEMS var n = args(0).toint for (c <- args(1)) { val conv = f(c) n = conv(n) println(n) Here we could equally well have written n = f(c)(n) directly (inside the loop). We can also map the string of instructions to a sequence of functions, and then fold them together with andthen (ie. using function composition¹): val initialnumber = args(0).toint val conversion = args(1).map(f).reduce(_ andthen _) println(conversion(initialnumber)) Normally there is at least one instruction (otherwise args.size would have been < 2 unless the user entered as second parameter, that would be mean-spirited though ), but if args(1) is empty, reduce will fail to avoid this we can use fold instead: val id = (n: Int) => n val conversion = args(1).map(f).fold(id)(_ andthen _) println(conversion(initialnumber)) It turns out that the Function-object has a function chain which handles the chaining of the functions: val conversion = Function.chain(args(1).map(f)) println(conversion(initialnumber)) ¹To be precise, the andthen- and the compose-methods works in different directions andthen applies this first, compose applies this last.

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

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Functions, Closures and Control Abstraction

Functions, Closures and Control Abstraction Functions, Closures and Control Abstraction Christopher Simpkins csimpkin@spsu.edu CS 3693, Fall 2011 Chris Simpkins (Georgia Tech) CS 3693 Scala 2011-09-07 1 / 1 Aside: drop and take (Optional) homework:

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software. Introduction to Netbeans This document is a brief introduction to writing and compiling a program using the NetBeans Integrated Development Environment (IDE). An IDE is a program that automates and makes

More information

Notes from the Boards Set BN19 Page

Notes from the Boards Set BN19 Page 1 The Class, String There are five programs in the class code folder Set17. The first one, String1 is discussed below. The folder StringInput shows simple string input from the keyboard. Processing is

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

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

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

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017 Expressions in JavaScript Jerry Cain CS 106AJ October 2, 2017 What is JavaScript? JavaScript was developed at the Netscape Communications Corporation in 1995, reportedly by a single programmer in just

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

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1 Hands-On Lab Introduction to Lab version: 1.0.0 Last updated: 12/10/2010 Page 1 CONTENTS OVERVIEW... 3 EXERCISE 1: TYPES IN... 4 Task 1 Observing Type Inference in... 4 Task 2 Working with Tuples... 6

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

...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

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

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

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Scala, Your Next Programming Language

Scala, Your Next Programming Language Scala, Your Next Programming Language (or if it is good enough for Twitter, it is good enough for me) WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that

More information

INTRODUCTION TO SCHEME

INTRODUCTION TO SCHEME INTRODUCTION TO SCHEME PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2019 Dalhousie University 1/110 SCHEME: A FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be passed as

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Lab 7: OCaml 12:00 PM, Oct 22, 2017 CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

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

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

Chapter 4. Computation. Bjarne Stroustrup.

Chapter 4. Computation. Bjarne Stroustrup. Chapter 4 Computation Bjarne Stroustrup www.stroustrup.com/programming Abstract Today, I ll present the basics of computation. In particular, we ll discuss expressions, how to iterate over a series of

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

C and C++ I. Spring 2014 Carola Wenk

C and C++ I. Spring 2014 Carola Wenk C and C++ I Spring 2014 Carola Wenk Different Languages Python sum = 0 i = 1 while (i

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions Grace Murray Hopper Expressions Eric Roberts CSCI 121 January 30, 2018 Grace Hopper was one of the pioneers of modern computing, working with

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Input, output, and sequence

Input, output, and sequence Chapter 29 Input, output, and sequence For this chapter, switch languages in DrRacket to Advanced Student Language. In the real world, we don t usually give a computer all the information it needs, all

More information

STUDENT LESSON A7 Simple I/O

STUDENT LESSON A7 Simple I/O STUDENT LESSON A7 Simple I/O Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O.

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 13 - Part 1 Thomas Wies New York University Review Last lecture Object Oriented Programming Outline Today: Scala Sources: Programming in Scala, Second

More information

Lesson 3: Accepting User Input and Using Different Methods for Output

Lesson 3: Accepting User Input and Using Different Methods for Output Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program

More information

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. Concepts Review 1. An algorithm is a sequence of steps to solve a problem. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. 3. A flowchart is the graphical

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree:

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree: Lecture 13 The Same Fringe Problem Given a binary tree: sealed trait BinTree [+A] case class Node [A]( lhs : BinTree [A], rhs : BinTree [A]) extends BinTree [A] case class Leaf [A]( x: A) extends BinTree

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

First Programming Language in CS Education The Arguments for Scala

First Programming Language in CS Education The Arguments for Scala First Programming Language in CS Education The Arguments for Scala WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that is under contract with CRC Press.

More information

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions Chapter 6: 6.1 Functions Introduction to Functions What Is A Function? Why Functions? We ve been using functions ( e.g. main() ). C++ program consists of one or more functions Function: a collection of

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready. CSE 341, Spring 2011, Final Examination 9 June 2011 Please do not turn the page until everyone is ready. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

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

Chapter 4 Computation

Chapter 4 Computation Chapter 4 Computation Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/spring_2011/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using C++ Abstract

More information

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to

More information

The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

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

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs. Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java

More information

Introduction to Object Oriented Systems Development. Practical Session (Week 2)

Introduction to Object Oriented Systems Development. Practical Session (Week 2) This practical session consists of three parts. Practical Session (Week 2) Part 1 (Tutorial). Starting with NetBeans In this module, we will use NetBeans IDE (Integrated Development Environment) for Java

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Errors. Lecture 6. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with

More information

Basic Programming Elements

Basic Programming Elements Chapter 2 Basic Programming Elements Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Introduction to Computer Programming

Introduction to Computer Programming Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x ); Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

Ex: If you use a program to record sales, you will want to remember data:

Ex: If you use a program to record sales, you will want to remember data: Data Variables Programs need to remember values. Ex: If you use a program to record sales, you will want to remember data: A loaf of bread was sold to Sione Latu on 14/02/19 for T$1.00. Customer Name:

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

Methods CSC 121 Fall 2014 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

HCA Tech Note 103. Expressions. Example: Conversion

HCA Tech Note 103. Expressions. Example: Conversion Expressions This technical note provides several examples on some of the common uses of expressions and the Compute element. The Compute element opens a lower level of HCA than available from the Visual

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Common LISP Tutorial 1 (Basic)

Common LISP Tutorial 1 (Basic) Common LISP Tutorial 1 (Basic) CLISP Download https://sourceforge.net/projects/clisp/ IPPL Course Materials (UST sir only) Download https://silp.iiita.ac.in/wordpress/?page_id=494 Introduction Lisp (1958)

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x ); Chapter 5 Methods Sections Pages Review Questions Programming Exercises 5.1 5.11 142 166 1 18 2 22 (evens), 30 Method Example 1. This is of a main() method using a another method, f. public class FirstMethod

More information

Option Values, Arrays, Sequences, and Lazy Evaluation

Option Values, Arrays, Sequences, and Lazy Evaluation Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

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

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values

More information