For example, if given Math.sqrt and 2.0, it computes Math.sqrt(Math.sqrt(2.0)).
Using the function:
def applyTwice[A](f: A => A, argument: A) = ???
Then testing the above example
If I correctly understand your question, you want to apply a function twice to an argument and test it too.
For example, if you need to apply Math.sqrt twice to an argument, you can achieve it as shown in below code:
val sqrt: Double => Double = Math.sqrt
def applyTwice[A](f: A => A, d: A) = {
f(f(d))
}
println(applyTwice[Double](sqrt, 625))
assert(applyTwice[Double](sqrt, 625) == 5.0) // will check if applyTwice return 5.0
Related
I am new in Scala and I just came across a situation that I would like someone could explain me.
When watching a Martin Odersky's course I found the following script he uses to explain functions which return a function
val tolerance = 0.0001
def isCloseEnough(x : Double, y : Double) = abs((x - y)/ x) / x < tolerance
def fixedPoint(f : Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
if(isCloseEnough(guess,next))next
else iterate(next)
}
iterate(firstGuess)
}
fixedPoint(x => 1 + x/2)(1)
def averageDamp(f: Double => Double)(x: Double) = (x + f(x))/2
def sqrt(x : Double) = fixedPoint(averageDamp(y => x/y))(1)
sqrt(2)
I understand perfectly how the scrip works, but I didn't expect this line:
fixedPoint(averageDamp(y => x/y))(1)
I know that thanks to Currying, Scala let us write functions with several parameter list. So the call to fixedPoint passing as parameter the result of avergaDamp and (1) is clear for me.
What I don't understand is how averageDamp uses the second parameter list of fixedPoint when it itself is inside the first parameter list. I though that would be a different scope, so I was expecting something like:
fixedPoint(averageDamp(y => x/y)(1))(1)
What is the property of Scala which allow us to implement the currying in this way? Is something similar to an implicit applied to a parameter list?
Thanks for your time
This is just how multiple parameter lists work: averageDamp(y => x/y) is equivalent to z => averageDamp(y => x/y)(z) and so its type is Double => Double.
If you wrote fixedPoint(averageDamp(y => x/y)(1))(1) as you expect, it would have a type mismatch because averageDamp(y => x/y)(1) has type Double and fixedPoint needs Double => Double.
Implicits aren't relevant here.
This line works because in the following expression:
fixedPoint(averageDamp(y => x/y))(1)
function "averageDamp(y => x/y)" is "passed by name" i.e. it will not be evaluated while passing to function "fixedPoint" but will be evaluated when it is called from inside "fixedPoint".
value "(1)" is just pass to argument "firstGuess" of "fixedPoint" which will be supplied to parameter "guess" inside the function definition in following expression:
val next = f(guess)
I am very new to Scala. I have been assigned the task of coding the Fast Fibonacci algorithm. I am finding it difficult when it comes to actually calling the function. The function takes a tuple of two and returns a tuple of two as a result. I don't know if my logic for fibStep is correct but I will get to that as soon as I can actually test the function. The following is what I have so far:
def fastFib(x: Long ): Long = {
def fibStep(x:(Long, Long)): (Long, Long) = {
//setting temporary variables a and b
def a = x._1
def b = x._2
//applying the fast Fibonacci algorithm
def c = a * (b * 2 - a)
def d = a * a + b * b
if (c+d % 2 == 0) return (c,d)
else return (d, c+d)
}
def tuple = (x-1,x-2)
return fibStep(tuple)
}
I need to pass the tuple (x-1,x-2) to fibStep. How do I do it? Thanks
The problem is in return statement. You trying to return tuple, instead of Long.
Fix:
def fastFib(x: Long ): Long = {
...
return fibStep(tuple)._1 // or ._2
}
Note: I'm not sure if your algorithm is correct
You've got a number of problems here.
def is used to define functions
val should be used to define variables
return should not be used. You 'return' a result simply by it being the last value in an expression.
A tuple is defined simply using parenthesis:
val myTuple = (1,2)
With this information you should be able to make a better attempt at it.
Output of below :
getNum(_);
getNum(3);
def getNum(num: Int) {
println("Num is " + num)
}
is
Num is 3
Why is getNum(_); not invoked ? How is _ used in this case ?
What you'd expect it to be? getNum(null) ?
The getNum(_); is translated into, something like:
{ x:Int => getNum(x) }
Which is a anonymous function and a value itself.
You could do for example:
val f = getNum(_)
f(42)
Then you'd see:
Num is 42
_ is used to partially apply a function. Partial application of a function produces another function with some of its parameters already applied.
val f = getNum(_) // partially apply
f(3) // apply the function
I am learning currying in scala and trying to apply my knowledge on the following piece of code.
object excercise {
def sqrt2(input : Double) : ((Double, Double) => Double, Double) => Double = {
def iter(guessFxn : (Double, Double) => Double, initial : Double) : Double = {
if (isGoodEnough(initial)) initial
else {
val newGuess: Double = guessFxn(initial, input)
iter(guessFxn, newGuess)
}
}
iter
def isGoodEnough(guess: Double): Boolean = {
math.abs(guess * guess - input ) / input < 0.001
}
}
println(sqrt2(2) ( (g: Double, c: Double) => (g + c / g) / 2, 1))
}
What i want to achieve is that sqrt2 should return a function which takes as 2 arguments
1. fxn(that takes 2 doubles as arg and return a double val) 2. double val
When i am trying to run the worksheet it is giving me error
Error: missing arguments for method iter;
follow this method with `_' if you want to treat it as a partially applied function
iter
^
Error: type mismatch;
found : Unit
required: ((Double, Double) => Double, Double) => Double
}
^
Error: missing arguments for method iter;
follow this method with `_' if you want to treat it as a partially applied function
iter
^
You just have to inverse the order of those piece of codes:
iter
def isGoodEnough(guess: Double): Boolean = {
math.abs(guess * guess - input ) / input < 0.001
}
becomes:
def isGoodEnough(guess: Double): Boolean = {
math.abs(guess * guess - input ) / input < 0.001
}
iter
Indeed, ending with an inner declared method involves a return type of Unit...that's not what you want.
Besides, you had this advice:
follow this method with `_' if you want to treat it as a partially applied function
iter
because as explains before, iter method is not returned (since its call is not made at the end of the method) and thus compiler expects it to be executed.
Of course, to be executed, it needs its compulsory parameters, that you didn't provide.
So the compiler "thinks" that you expected to partially apply the function but badly. Note than a partially applied function is not the same concept than a partial function, that has a different meaning ... ).
It would allow to defer the call, and it's mostly used when dealing standard function (not curried), where we might need to provide only the first parameter and later the following.
Example of partially applied function:
def sum(i: Int, j: Int){...}
calls:
sum 1 _ //just the second parameter needs to be applied later.
sum _ //none parameter is specified, would need to specify both later.
sum 1 2 //complete call, not partially applied so
You can find a good use case of partially applied function here.
Note: this is a theoretical question, I am not trying to fix anything, nor am I trying to achieve any effect for a practical purpose
When creating a lambda in Scala using the (arguments)=>expression syntax, can the return type be explicitly provided?
Lambdas are no different than methods on that they both are specified as expressions, but as far as I understand it, the return type of methods is defined easily with the def name(arguments): return type = expression syntax.
Consider this (illustrative) example:
def sequence(start: Int, next: Int=>Int): ()=>Int = {
var x: Int = start
//How can I denote that this function should return an integer?
() => {
var result: Int = x
x = next(x)
result
}
}
You can always declare the type of an expression by appending : and the type. So, for instance:
((x: Int) => x.toString): (Int => String)
This is useful if you, for instance, have a big complicated expression and you don't want to rely upon type inference to get the types straight.
{
if (foo(y)) x => Some(bar(x))
else x => None
}: (Int => Option[Bar])
// Without type ascription, need (x: Int)
But it's probably even clearer if you assign the result to a temporary variable with a specified type:
val fn: Int => Option[Bar] = {
if (foo(y)) x => Some(bar(x))
else _ => None
}
Let say you have this function:
def mulF(a: Int, b: Int): Long = {
a.toLong * b
}
The same function can be written as lambda with defined input and output types:
val mulLambda: (Int, Int) => Long = (x: Int, y: Int) => { x.toLong * y }
x => x:SomeType
Did not know the answer myself as I never had the need for it, but my gut feeling was that this will work. And trying it in a worksheet confirmed it.
Edit: I provided this answer before there was an example above. It is true that this is not needed in the concrete example. But in rare cases where you'd need it, the syntax I showed will work.