Download presentation
Presentation is loading. Please wait.
1
1 Gentle Introduction to Programming Session 2: Functions
2
2 Review General terms in CS & programming Scala variables & types operators if / while / for Compiler / Interpreter Eclipse / Scala shell
3
3 Today More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Guest lecture by Prof. Nir Shavit (10:10) Home work review Functions More on control structures Home work
4
4 Var versus Val val – “final” variable / imutable Example:
5
5 Strings val s : String = “ABC” A sequence of characters Have additional functionality (expressed by methods)
6
6 Application Programming Interface (API) How could I know that String has a method toLowerCase? How about checking the Scala API? http://www.scala-lang.org/docu/files/api/index.html http://www.scala-lang.org/docu/files/api/index.html Oops…
7
7 Java and Scala Scala is fully compatible with Java Actually, Scala is compiled into Java Bytecode And here is the String API (finally…) http://java.sun.com/j2se/1.5/docs/api/java/lang/String.html http://java.sun.com/j2se/1.5/docs/api/java/lang/String.html
8
8 Type Inference Scala’s ability to figure out types you leave off
9
9 Variable Scope output MultiTable.scala
10
10 Programming Style Comments: //, /* */ Indentation (cntl + i in eclipse) Meaningful variables names Why is it important?
11
11 Today More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Guest lecture by Prof. Nir Shavit Home work review Functions More on control structures Home work
12
12 Exercise 0 Write your first “Hello World!” program in Scala: Use the interpreter In Eclipse Make sure it compiles and executes properly Congratulations! Do you want us to do it together? Hello.scala
13
13 Fibonacci Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/Fibonacci_number
14
14 Exercise 1 Write a program that receives from the user an integer n > 0 and prints to the screen the n th Fibonacci number a.Use a “for” loop b.Use a “while” loop
15
15 Solution ? Fibonacci.scala
16
16 Command Line Arguments In Eclipse
17
17 Command Line Arguments In Eclipse
18
18 Exercise 2 Write a program that receives from the user two integers 0 < n1 < n2 and prints to the screen all prime numbers between n1 and n2 Divide the problem to smaller sub-problems: How would you traverse over all the numbers between n1 and n2? How would you be sure that a given number is a prime?
19
19 Solution Primes.scala
20
20 Today More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Guest lecture by Prof. Nir Shavit Home work review Functions More on control structures Home work
21
21 Functions A group of declarations and statements that is assigned a name Effectively, a named statement block Usually has a value A sub-program When we write our program we always define a function named main Inside main we can call other functions Which can themselves use other functions, and so on…
22
22 What are They Good For? Generalize a repeated set of instructions We don’t have to keep writing the same thing over and over Solve bugs once… They can break your problem down into smaller sub-tasks Easier to solve complex problems They make a program much easier to read and maintain Abstraction – we don’t have to know how a function is implemented to use it
23
23 In Short Why do we need functions? Code reusability Modularity Abstraction
24
24 Function Definition in Scala
25
25 Example
26
26 Example
27
27 Function Output The last statement defines returned value to the calling function The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type) If no value is to be returned, the return-type of the function should be set to ‘Unit’, and a unit value is returned
28
28 Types of Functions Method – member of some object (e.g., String – toLowerCase) Local functions: functions nested within functions Function literals (First-class functions), e.g: (x:Int) => x+1 Why do we need it anyway? Function values (e.g., val f = (x:Int => x+1))
29
29 Example: Nested Functions PrimesNested.Scala
30
30 There are many ways to define functions in Scala FuncDef.scala
31
31 Closures (x : Int) => x + more // how much more? free variable
32
32 Closures (Cont.)
33
33 Can procedures get and return procedures? In Scala a function can: Return a function as its return value, Receive functions as arguments. Why is this useful?
34
34 Consider the Following Three Sums 1 + 2 + … + 100 = (100 * 101)/2 1 + 4 + 9 + … + 100 2 = (100 * 101 * 102)/6 1 + 1/3 2 + 1/5 2 + … + 1/101 2 ~ 2 /8 In mathematics they are all captured by the notion of a sum:
35
35 In Scala Generalization:
36
36 The “Sum” Function
37
37 Usage (HigherOrderFunc.scala)
38
38 How Does it Work? sum += ((x:Int) => x)(i) i = ((x:Int) => x+1)(i)
39
39 Integration as a Function Integration under a curve f is approximated by dx ( f(a) + f(a + dx) + f(a + 2dx) + … + f(b) ) a b dx f
40
40 Integration as a Function (Cont.) a b dx f
41
41 arctan(a) = ∫(1/(1+y 2 ))dy 0 a Integration.scala
42
42 Function as a Contract If the operands have the specified types, the procedure will result in a value of the specified type otherwise, its behavior is undefined (maybe an error, maybe random behavior) A contract between the caller and the procedure. Caller responsible for argument number and types function responsible to deliver correct result
43
43 Example
44
44 The Functions “Stack” g() ->h() f() ->g() main -> f()
45
45 Today More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Guest lecture by Prof. Nir Shavit Home work review Functions More on control structures Home work
46
46 Scala’s Control Strctures All of Scala’s control structures result in some value: Example: println(if (price > 100) “expensive” else “cheap”)
47
47 Example – MultiTable
48
48 Today More Scala: var / val Strings & API Defining variables (type inference) Variable scope Importance of style Guest lecture by Prof. Nir Shavit Home work review Functions More on control structures Home work
49
49 Approximating Square Root Given integer x > 0, how to find an approximation of x? Newton was the first to notice that for any positive n, and when x 0 =1, the following series converges to sqrt(n):
50
50 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = 1.416666 x/g = 24/17g = ½ (17/12 + 24/17) = 577/408 = 1.4142156 Algorithm: Make a guess g Improve the guess by averaging g, x/g Keep improving the guess until it is good enough Example: calculate the square root of 2
51
51 Exercise 1 Write a program that receives from the user: An integer x > 0 A double representing the approximation’s accuracy Calculates an approximation of x within the required accuracy Use the function Math.abs(x) which returns the absolute value of x
52
52 Exercise 2 Write a function that uses the formula : 2 /6=1/1+1/4+1/9+1/16+…+1/n 2 (where n goes to infinity) in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of Write a program that gets an integer n from the user, and approximate using n terms of the above formula Use a nested function sum, with signature:
53
53 Exercise 3 Write a function deriv : Input: a function f (Double=>Double), accuracy dx Output: function df (Double=>Double), the derivative of f. df (x) = (f(x+dx) – f(x))/dx Define a few simple functions (linear, square) and calculate their derivative at various points received by command line arguments
54
54 If time allows – surprise! Debugger
55
55 The Debugger Some programs may compile correctly, yet not produce the desirable results These programs are valid and correct Scala programs, yet not the programs we meant to write! The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program
56
56 Debugger – Add Breakpoint Right click on the desired line “Toggle Breakpoint”
57
57 Debugger – Start Debugging breakpoint debug
58
58 Debugger – Debug Perspective
59
59 Debugger – Debugging Current state Current location Back to Scala perspective
60
60 Want More Exercises ?
61
61 Exercise – Approximate (given accuracy) Modify the previous function that approximates (exercise 2). The function should accept an argument specifying the desired accuracy, and keep adding terms until the contribution of the next term drops below this level Write a program that gets a (small) double, epsilon, from the user, and approximates within this function Hint: change the sum method
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.