I always get "1" as result. :(
Whats wrong with this function?
def power(base: Int, exp: Int): BigInt = {
def _power(result: BigInt, exp: Int): BigInt = exp match {
case 0 => 1
case _ => _power(result*base, exp-1)
}
_power(1, exp)
}
you have to replace so: case 0 => result
probably not relevant for OP but I used this answer as an example for something and this version works:
def power(base: Int, exp: Int): BigInt = {
def _power(result: BigInt, exp: Int): BigInt = exp match {
case 0 => 1
case 1 => result
case _ => _power(result*base, exp-1)
}
_power(base, exp)
}
Better, tail-recursive solution (stack-safe) may look like:
def power(base: Int, exp: Int): BigInt {
#scala.annotation.tailrec
def loop(x: BigInt, n: Long, kx: BigInt): BigInt = {
if (n == 1) x * kx
else {
if (n % 2 == 0)
loop(x * x, n / 2, kx)
else
loop(x, n - 1, x * kx) // O(log N) time complexity!
}
}
if (n == 0) 1
else {
val pow = loop(base, Math.abs(exp.toLong), 1)
if (n > 0) pow else 1 / pow
}
}
I'm new to Scala and I had the same task, liked the idea with match. Used your code as an example and this is what I've got
def power(base: Int, exp: Int): BigDecimal = {
if (exp == 0) 1 else {
#tailrec
def _power(result: BigDecimal, exp: Int): BigDecimal = exp match {
case 0 => result
case pos if (pos > 0) => _power(result * base, exp - 1)
case neg if (neg < 0) => _power(result / base, exp + 1)
}
_power(1, exp)
}
}
Don't know what #tailrec means yet but I guess it may be useful, IDEA hinted me with that :)
Related
This is a follow-up to my previous question:
Suppose I have a few functions that return scalaz.Validaton:
type Status[A] = ValidationNel[String, A]
val isPositive: Int => Status[Int] =
x => if (x > 0) x.success else s"$x not positive".failureNel
val isNegative: Int => Status[Int] =
x => if (x < 0) x.success else s"$x not negative".failureNel
I can write a new function makeX
case class X(x1: Int, // should be positive
x2: Int, // should be positive
x3: Int) // should be negative
val makeX: (Int, Int, Int) => Status[X] = (x1, x2, x3) =>
(isPositive(x1) |#| isPositive(x2) |#| isNegative(x3)) (X.apply _)
My question is: How to write makeX in point-free style
Here's a funky way to make it pointfree:
val makeX: (Int, Int, Int) => Status[X] = isPositive(_) |#| isPositive(_) |#| isNegative(_) apply X
I'm having hard time understanding what the following means in scala:
f: Int => Int
Is the a function?
What is the difference between f: Int => Intand def f(Int => Int)?
Thanks
Assuming f: Int => Int is a typo of val f: Int => Int,
and def f(Int => Int) is a typo of def f(i: Int): Int.
val f: Int => Int means that a value f is Function1[Int, Int].
First, A => B equals to =>[A, B].
This is just a shortcut writing, for example:
trait Foo[A, B]
val foo: Int Foo String // = Foo[Int, String]
Second, =>[A, B] equals to Function1[A, B].
This is called "type alias", defined like:
type ~>[A, B] = Foo[A, B]
val foo: Int ~> String // = Foo[Int, String]
def f(i: Int): Int is a method, not a function.
But a value g is Function1[Int, Int] where val g = f _ is defined.
f: Int => Int
means that type of f is Int => Int.
Now what does that mean? It means that f is a function which gets an Int and returns an Int.
You can define such a function with
def f(i: Int): Int = i * 2
or with
def f: Int => Int = i => i * 2
or even with
def f: Int => Int = _ * 2
_ is a placeholder used for designating the argument. In this case the type of the parameter is already defined in Int => Int so compiler knows what is the type of this _.
The following is again equivalent to above definitions:
def f = (i:Int) => i * 2
In all cases type of f is Int => Int.
=>
So what is this arrow?
If you see this arrow in type position (i.e. where a type is needed) it designates a function.
for example in
val func: String => String
But if you see this arrow in an anonymous function it separates the parameters from body of the function. For example in
i => i * 2
To elaborate just slightly on Nader's answer, f: Int => Int will frequently appear in a parameter list for a high order function, so
def myHighOrderFunction(f : Int => Int) : String = {
// ...
"Hi"
}
is a dumb high order function, but shows how you say that myOrderFunction takes as a parameter, f, which is a function that maps an int to an int.
So I might legally call it like this for example:
myHighOrderFunction(_ * 2)
A much more illustrative example comes from Odersky's Programming Scala:
object FileMatcher {
private def filesHere = (new java.io.File(".")).listFiles
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere if matcher(file.getName))
yield file
def filesEnding(query: String) = filesMatching(_.endsWith(query))
def filesContaining(query: String) = filesMatching(_.contains(query))
def filesRegex(query: String) = filesMatching(_.matches(query))
}
Here filesMatching is a high order function, and we define three other functions that call it passing in different anonymous functions to do different kinds of matching.
Hope that helps.
What's the difference between these two definitions?:
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)
What is the purpose of each?
The second is curried, the first isn't. For a discussion of why you might choose to curry a method, see What's the rationale behind curried functions in Scala?
sayTwords2 allows the method to be partially applied.
val sayHelloAnd = sayTwords2("Hello")
sayHelloAnd("World!")
sayHaelloAnd("Universe!")
Note you can also use the first function in the same way.
val sayHelloAnd = sayTwords("Hello", _:String)
sayHelloAnd("World!")
sayHelloAnd("Universe!")
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)
The first contains a single parameter list. The second contains multiple parameter lists.
They differ in following regards:
Partial application syntax. Observe:
scala> val f = sayTwords("hello", _: String)
f: String => Unit = <function1>
scala> f("world")
hello world
scala> val g = sayTwords2("hello") _
g: String => Unit = <function1>
scala> g("world")
hello world
The former has a benefit of being positional syntax. Thus you can partially apply arguments in any positions.
Type inference. The type inference in Scala works per parameter list, and goes from left to right. So given a case, one might facilitate better type inference than other. Observe:
scala> def unfold[A, B](seed: B, f: B => Option[(A, B)]): Seq[A] = {
| val s = Seq.newBuilder[A]
| var x = seed
| breakable {
| while (true) {
| f(x) match {
| case None => break
| case Some((r, x0)) => s += r; x = x0
| }
| }
| }
| s.result
| }
unfold: [A, B](seed: B, f: B => Option[(A, B)])Seq[A]
scala> unfold(11, x => if (x == 0) None else Some((x, x - 1)))
<console>:18: error: missing parameter type
unfold(11, x => if (x == 0) None else Some((x, x - 1)))
^
scala> unfold(11, (x: Int) => if (x == 0) None else Some((x, x - 1)))
res7: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> def unfold[A, B](seed: B)(f: B => Option[(A, B)]): Seq[A] = {
| val s = Seq.newBuilder[A]
| var x = seed
| breakable {
| while (true) {
| f(x) match {
| case None => break
| case Some((r, x0)) => s += r; x = x0
| }
| }
| }
| s.result
| }
unfold: [A, B](seed: B)(f: B => Option[(A, B)])Seq[A]
scala> unfold(11)(x => if (x == 0) None else Some((x, x - 1)))
res8: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Forgive me if this has already been asked elsewhere. I have a Scala syntax question involving function-values and implicit parameters.
I'm comfortable using implicits with Scala's currying feature. For instance if I had a sum function and wanted to make the second argument an implicit:
scala> def sum(a: Int)(implicit b: Int) = a + b
sum: (a: Int)(implicit b: Int)Int
Is there a way to do this using the function-value syntax? Ignoring the implicit for a moment, I typically write curried function-values like this:
scala> val sum2 = (a: Int) => (b: Int) => a + b
sum: (Int) => (Int) => Int = <function1>
However, the function signature in the second approach is much different (the currying is being expressed explicitly). Just adding the implicit keyword to b doesn't make much sense and the compiler complains as well:
scala> val sum2 = (a: Int) => (implicit b: Int) => a + b
<console>:1: error: '=>' expected but ')' found.
val sum2 = (a: Int) => (implicit b: Int) => a + b
^
Furthermore partially-applying sum from the very first approach to get a function-value causes problems as well:
scala> val sumFunction = sum _
<console>:14: error: could not find implicit value for parameter b: Int
val sumFunction = sum _
^
This leads me to believe that functions that have implicit parameters must have said parameters determined when the function-value is created, not when the function-value is applied later on. Is this really the case? Can you ever use an implicit parameter with a function-value?
Thanks for the help!
scala> val sum2 = (a: Int) => {implicit b: Int => a + b}
sum2: (Int) => (Int) => Int = <function1>
This will just make b an implicit value for the scope of the function body, so you can call methods that expect an implicit Int.
I don't think you can have implicit arguments for functions since then it is unclear what the function is. Is it Int => Int or () => Int?
The closest I found is:
scala> case class Foo(implicit b: Int) extends (Int => Int) {def apply(a: Int) = a + b}
defined class Foo
scala> implicit val b = 3
b: Int = 3
scala> Foo()
res22: Foo = <function1>
scala> res22(2)
res23: Int = 5
In this snippet
scala> val sum2 = (a: Int) => (b: Int) => a + b
sum: (Int) => (Int) => Int = <function1>
Note that the precise type of sum2 is Function1[Int, Function1[Int, Int]]. It could also be written as
val sum2 = new Function1[Int, Function1[Int, Int]] {
def apply(a: Int) = new Function1[Int, Int] {
def apply(b: Int) = a + b
}
}
Now, if you try to make b implicit, you get this:
scala> val sum2 = new Function1[Int, Function1[Int, Int]] {
| def apply(a: Int) = new Function1[Int, Int] {
| def apply(implicit b: Int) = a + b
| }
| }
<console>:8: error: object creation impossible, since method apply in trait Function1 of type (v1: Int)Int is not defined
def apply(a: Int) = new Function1[Int, Int] {
^
Or, in other words, Function's interfaces do not have implicit parameters, so anything with an implicit parameter is not a Function.
Try overloading the apply method.
scala> val sum = new Function1[Int, Function1[Int, Int]] {
| def apply(a: Int) = (b: Int) => a + b
| def apply(a: Int)(implicit b: Int) = a + b
|}
sum: java.lang.Object with (Int) => (Int) => Int{def apply(a:Int)(implicit b: Int): Int} = <function1>
scala> sum(2)(3)
res0: Int = 5
scala> implicit val b = 10
b: Int = 10
scala> sum(2)
res1: Int = 12
How can I return a function side-effecting lexical closure1 in Scala?
For instance, I was looking at this code sample in Go:
...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())
prints
1 2 3 5 8
And I can't figure out how to write the same in Scala.
1. Corrected after Apocalisp comment
Slightly shorter, you don't need the return.
def fib() = {
var a = 0
var b = 1
() => {
val t = a;
a = b
b = t + b
b
}
}
Gah! Mutable variables?!
val fib: Stream[Int] =
1 #:: 1 #:: (fib zip fib.tail map Function.tupled(_+_))
You can return a literal function that gets the nth fib, for example:
val fibAt: Int => Int = fib drop _ head
EDIT: Since you asked for the functional way of "getting a different value each time you call f", here's how you would do that. This uses Scalaz's State monad:
import scalaz._
import Scalaz._
def uncons[A](s: Stream[A]) = (s.tail, s.head)
val f = state(uncons[Int])
The value f is a state transition function. Given a stream, it will return its head, and "mutate" the stream on the side by taking its tail. Note that f is totally oblivious to fib. Here's a REPL session illustrating how this works:
scala> (for { _ <- f; _ <- f; _ <- f; _ <- f; x <- f } yield x)
res29: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#d53513
scala> (for { _ <- f; _ <- f; _ <- f; x <- f } yield x)
res30: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#1ad0ff8
scala> res29 ! fib
res31: Int = 5
scala> res30 ! fib
res32: Int = 3
Clearly, the value you get out depends on the number of times you call f. But this is all purely functional and therefore modular and composable. For example, we can pass any nonempty Stream, not just fib.
So you see, you can have effects without side-effects.
While we're sharing cool implementations of the fibonacci function that are only tangentially related to the question, here's a memoized version:
val fib: Int => BigInt = {
def fibRec(f: Int => BigInt)(n: Int): BigInt = {
if (n == 0) 1
else if (n == 1) 1
else (f(n-1) + f(n-2))
}
Memoize.Y(fibRec)
}
It uses the memoizing fixed-point combinator implemented as an answer to this question: In Scala 2.8, what type to use to store an in-memory mutable data table?
Incidentally, the implementation of the combinator suggests a slightly more explicit technique for implementing your function side-effecting lexical closure:
def fib(): () => Int = {
var a = 0
var b = 1
def f(): Int = {
val t = a;
a = b
b = t + b
b
}
f
}
Got it!! after some trial and error:
def fib() : () => Int = {
var a = 0
var b = 1
return (()=>{
val t = a;
a = b
b = t + b
b
})
}
Testing:
val f = fib()
println(f(),f(),f(),f())
1 2 3 5 8
You don't need a temp var when using a tuple:
def fib() = {
var t = (1,-1)
() => {
t = (t._1 + t._2, t._1)
t._1
}
}
But in real life you should use Apocalisp's solution.