- if CBV terminates, then so does CBN - since CBN will evaluate less than or equal parameters than CBV
- CBV avoids repeated recomputation of values
- force scala to do CBN, by defining
def fun(x:Int, y:=>Int)
- disjunction and conjunction (&& and ||) are short-circuit operators - the right side will only be evaluated in certain cases.
- in certain cases like
if(r==0) return 1
there is an errorScala: type mismatch; found : Unit required: Boolean
- this happens because you have to have an else clause, otherwise the type checker doesn't know what the return type is when it's not the case
return fn(a-1)
is tail recursive butreturn n * fn(a-1)
is notimport scala.annotation.tailrec
and@tailrec
annotation is a good way of verifying whether a function is tail-recursive
val
vsvar
: val is immutable, while var is mutable.- create a function returnin new object with some activity
def addRational(r:Rational, s:Rational):Rational = new Rational(r.num*s.num, r.den*s.den)
override def toString = num + "/" + den
- Instead of using a mutable variable, try making the variable a function parameter. If it isn't already a parameter of the function, define a function inside it that has the parameter and use recursion inside that function to change the value of the parameter. *return statement in a closure does not look like a return statement: it's hard to understand which function should return, the closure in progress — or the main one?
##define a function taking another function as input
def sum(f: Int => Int)
def sum(x:Int): Int => Boolean = ...
or
type RetType = Int => Boolean
def sum(x:Int): RetType = ...
NOTE: this function starts from a to b
def sum(f: Int => Int): (Int, Int) => Int = {
def sumF(a:Int, b:Int):Int = {
if(a>b) return 0
else f(a) + sumF(a+1, b)
}
sumF
}
or
def sum2(f:Int=>Int)(a:Int, b:Int): Int = {
if(a>b) return 0
else f(a) + sum2(f)(a+1, b)
}
NOTE: the first bracket (f:Int=>Int)
is the parameters of the upper function and the second bracket (a:Int, b:Int)
is actually the formal parameters of the inner function. Return parameters of the whole function is the return parameter of the inner (returning) function.
def f (args1)(args2)...(argsn) =E
is actually
def f(args1)(args2)...(argsn-1) = {def g(argsn) = E; g}
or in terms of anonymous functions
def f(args1)(args2)...(argsn-1) = (argsn => E)
Expanding :
def f = (args1 => (args2 => (args3 => ... (argsn => E))))
##usage
sumC = sum(x=>x*x*x)
sumC(1,2)
or
def cube(x:Int):Int = {
x*x*x
}
sum(cube)(1,2)
if (a>b) return zero
else combine( f(a), mapreduce(f,combine,zero)(a+1,b))
}```
therefore
```sum(f:Int => Int)(a:Int, b:Int):Int = mapreduce(f, (x,y)=>x*y, 0)(a,b) ```