Helper method with accumulators in Scala [closed] - scala

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Below is an example used to illustrate how to use immutable variables. (1) What function is this method performing and (2) which portion is considered the accumulator?
def fib(n: Int): Int = {
def fibIter(i: Int, a: Int, b: Int): Int =
if (i == n) a else fibIter(i+1, b, a+b)
fibIter(0, 0, 1)
}

As mentioned by #jwvh in his comment, this is a function for computing the nth term of the Fibonacci sequence.
This particular implementation is tail recursive and uses the inner function fibIter as an "accumulator." Often in order to code a tail recursive implementation of a recursive function, it is useful to define an inner tail recursive function that accumulates the desired result. The outer function will the call this inner function with some default params. Sometimes this inner function is called "accumulate" or "go" or "loop", etc.
Here would be my preferred implementation of a Fibonacci similar to the above...
def fibonacci(n: Int): Int = {
#annotation.tailrec
def iterate(i: Int, a: Int, b: Int): Int =
if (i == n) a else iterate(i+1, b, a+b)
iterate(0, 0, 1)
}
...here I prefer to call the inner function iterate because this is a more accurate description of what the function is doing (i.e., it isn't really accumulating anything).

Related

Factorial with Scala [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am new to Scala and tying to understand recursion and tail recursion. When I write the program in single line, it's always giving me StackOverflow error, even for n=1 -
object Recursion extends App {
def factorial(n: Int): Int = //if (n<=1) 1
n * factorial( n - 1 )
println( factorial( 1 ) )
}
vs
object Recursion extends App {
def factorial(n: Int): Int = (
if (n <= 1) 1
else n * factorial( n - 1 )
)
println( factorial( 8 ) )
}
Gives correct value - 40320
Got it, without if (n<=1), it's going to infinite loop. That's why it never comes out and give this error.
In problems solved via recursion, you must have a "branch/condition" that breaks the recursion and returns the accumulated value (aka pops the stack), or else the problem would never stop in theory; in practise all the calls to the function eventually overloads the memory allocated for the stack (i.e. StackOverflow error)
Notice also, that your function is recursive, but it is not tail recursive. For it to be tail recursive, the recursive call must the very last step.
To make it tail recursive you would have to do something like:
def factorial(n: Int): Int = {
#tailrec
def helper(n: Int, acc: Int): Int = {
if (n == 1) acc
else helper(n-1, n*acc)
}
helper(n, 1)
}
In your case, the last step is the multiplication n*factorial(n-1). In my case, it is truly a call to itself.
Just to make things clear, in my example, factorial is not recursive (tail or otherwise), but the inner function helper is tail recursive.

val cond: (Int, Int) => Boolean = (...) what does this scala code mean? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm confused about the first line of code.
And what's the difference between the first line and the second line?
val cond: (Int, Int) => Boolean = (...) //confused
val cond = (x: Int, y: Int) => x > y //anonymous function
It can be a bit daunting at first, but all Scala declarations are the same shape:
val <name>[: <type>] = <value>
If the type is not there the compiler will set it to the type of the value
So the first case breaks down like this:
The name is cond
The type is (Int, Int) => Boolean
The value is (...)
The second case breaks down like this:
The name is cond
The value is (x: Int, y: Int) => x > y
The type is inferred to be (Int, Int) => Boolean
In both cases cond is a function that takes two Ints and returns a Boolean.

In which scenario '=' used and '=>' used in scala? [duplicate]

This question already has an answer here:
Can anyone explain how the symbol "=>" is used in Scala
(1 answer)
Closed 4 years ago.
I am new to scala and I confused little bit with = and =>, I don't know in which scenario exactly = used and => used.
#RamanMishra's comment is correct, however I would like to expand it a bit hopping it becomes more clear to you.
a = b means a is now equals to b (in the imperative meaning of the word, which is better understood as assignment).
It is used in many places, including when defining a function\method, for example
def sum(a: Int, b: Int): Int = a + b
The above statement can be readed as:
"We defined a function with name sum which takes two parameters (a & b) both of type Int and returns an Int. And its body\implementation is 'equals' to a + b".
a => b means, there is a function which takes a parameters list a and has a body b, it is used a couple of places, including anonymous functions and higher-order functions.
val anonymous: Int => Int = x => x + 1
The above statement can be readed as:
"We defined a value called anonymous, whose type is a function with one parameter of type Int and a return type Int, which is 'equals' to the 'anonymous' function which takes one parameter x (its type is inferred in by the context, in this type the explicit type signature before) and its body is x + 1"
def higherOrder(x: Int, f: Int => Int): Int = f(x)
The above statement can be readed as:
"There is a function (sum), which takes another function as a parameter (f), the later is a function of type Int to Int".
Edit
As #Aki suggested, the => is also used in pattern matching to separate the cases and the block of code to execute for each one.
def fact(n: Long): Long = n match {
case 0L => 1L
case n => n * fact(n - 1)
}
"This is somewhat similar to a parameter list => function body, as the above examples".
PS: This is a 101 Scala question, SO is not the best place for such questions, because there is probably enough resources on the internet - like this cheatsheet, or better places to ask - like the scala gitter channel.

Understanding currying Scala [duplicate]

This question already has answers here:
Understanding Currying in Scala
(3 answers)
Closed 4 years ago.
def sum(f: Int => Int): (Int, Int) => Int = {
def sumF(a: Int, b: Int): Int =
if (a > b) 0
else f(a) + sumF(a + 1, b)
sumF
}
def sumCubes = sum(a => a * a * a)
sumCubes // output Function2
sumCubes(1,10) // output 3025.
sumCubes() // doesn't work
I feel I dont understand currying well enough. In the first statement , we are calling sumCubes without parameters , hence sum gets called with the anonymous function as parameter and returns a function2.
Whats really happening in 2nd and 3rd invocation ,
Why are we able to do
sum(a => a * a * a)(1,10)
but not
sumCubes()(1,10)
My understanding is that in sum(a => a * a * a)(1,10) , we are partially applying sum to the anonymous function, which returns a Function2 ,which is applied to the second pair of parameters (1,10) and hence we are getting 3025,
However the same should happen in case of sumCubes()(1,10) , invoking sumCubes without parameters first , would inturn invoke sum with the anonymous function and the Function2 returned would be applied to (1,10)
Why does sumCubes(1,10) work but not sumCubes()(1,10) , shouldn't sumCubes and sumCubes() mean the same thing , invocation of function sumCubes. Also if a simple reference sumCubes is invoking it , how can I pass it around. I feel like I am not understanding something fundamental about Scala.
Scala's methods can have multiple argument lists.
For example, here is a method foo that has ten argument lists, of which the first seven are empty:
def foo()()()()()()()(a: Int)(b: Int)(c: Int): Int = a + b + c
You can invoke it as follows:
println(foo()()()()()()()(1)(20)(300))
and it will print 321.
Note that when you invoke a method, the number of argument lists, as well as the number of arguments in each list (and also their types) have to match the declaration.
Another example. The following method has two argument lists:
def bar(i: Int)(f: Int => Int) = f(i)
you can invoke it as follows:
bar(42)(x => x * x)
but not as
bar()(x => x * x)
bar()(42)(x => x * x)
bar(42)()
or anything like it.
Completely analogously, if you have defined a method with zero argument lists
def baz = (x: Int) => x * x
then you must invoke it with zero argument lists too:
baz
Since it returns an Int => Int function, you can of course apply the result to an Int:
baz(42)
which is the same as (baz)(42), but you cannot do the following:
baz()(42)
because baz itself has no argument lists, and () does not contain a single integer argument.
Note that all of the above is actually a simplification: under certain circumstances, methods that have an empty argument list can be called without parentheses, i.e. def foo(): Unit = ... can be invoked as foo, without (). This is a somewhat strange feature, and I can't say exactly why it's there. My best guess would be: it has something to do with java-interop, where you really want to omit parentheses on zero-ary getters.

What is the underscore character used for in Scala? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are all the uses of an underscore in Scala?
When I follow a particular tutorial, I happen to see that the following two usages gives the same result. I understand the first one, but I do not understand why the 2nd one also works. Can someone give me an explanation, and at the same time give a summary of _ usage?
def sum (a:Int, b:Int) = a + b
val sumAsFunction1 = sum(_:Int, _:Int)
// I understand this, _ used as placeholder of parameters
val sumAsFunction2 = sum _
// why this usage has the same effect as sumAsFunction1?
This is one of the few places where eta-expansion mechanism needs some help. Consider the simpler example:
def foo() = {
println("foo");
42
}
val bar1 = foo
val bar2 = foo _
There is a fundamental difference between bar1 and bar2. The former one is interpreted as call foo and assign value to bar while the latter: Change method foo into a function and assign it to bar2. As a result bar1 is just a simple Int variable while bar2 is actually a function that will call original foo() method (and print "foo").
The underscore is used for a lot of things, but in this situation, it's used to denote that you want the un-called version of the sum function.
You define sum(a: Int, b:Int) = a + b, so think of sum _ as an anonymous function that takes the two arguments and returns their sum. You can pass the function around, since it's an instance of Function2[Int,Int,Int].