I have a newbie question for ScalaCheck which I am playing around with for the first time.
Is it possible to create a Gen[Int] which will progress linearly from say 0 to N.
Such that when I use forAll in ScalaCheck it will increase the input Int by 1.
I would like this example to test with an increasing value
"Increase" should "always increase" in {
forAll(validNumbers){ i:Int =>
increase(i) should be (i + 1)
}
}
Maybe this destroys ScalaChecks purpose and I should just test this way in ScalaTest.
You could do something like this:
def validNumbers(n: Int): Gen[Int] = Gen.resultOf[Int, Int] {
new (Int => Int) {
val current = (0 to n).iterator
def apply(i: Int): Int = {
if(current.hasNext) current.next else sys.error("No more numbers")
}
}
}
However I think you are indeed right, that this destroys ScalaChecks purpose. A simple for-loop would do better in this case.
Related
Learning Scala and functional programming in general. In the following tail-recursive factorial implementation:
def factorialTailRec(n: Int) : Int = {
#tailrec
def factorialRec(n: Int, f: => Int): Int = {
if (n == 0) f else factorialRec(n - 1, n * f)
}
factorialRec(n, 1)
}
I wonder whether there is any benefit to having the second parameter called by value vs called by name (as I have done). In the first case, every stack frame is burdened with a product. In the second case, if my understanding is correct, the entire chain of products will be carried over to the case if ( n== 0) at the nth stack frame, so we will still have to perform the same number of multiplications. Unfortunately, this is not a product of form a^n, which can be calculated in log_2n steps through repeated squaring, but a product of terms that differ by 1 every time. So I can't see any possible way of optimizing the final product: it will still require the multiplication of O(n) terms.
Is this correct? Is call by value equivalent to call by name here, in terms of complexity?
Let me just expand a little bit what you've already been told in comments.
That's how by-name parameters are desugared by the compiler:
#tailrec
def factorialTailRec(n: Int, f: => Int): Int = {
if (n == 0) {
val fEvaluated = f
fEvaluated
} else {
val fEvaluated = f // <-- here we are going deeper into stack.
factorialTailRec(n - 1, n * fEvaluated)
}
}
Through experimentation I found out that with the call by name formalism, the method becomes... non-tail recursive! I made this example code to compare factorial tail-recursively, and factorial non-tail-recursively:
package example
import scala.annotation.tailrec
object Factorial extends App {
val ITERS = 100000
def factorialTailRec(n: Int) : Int = {
#tailrec
def factorialTailRec(n: Int, f: => Int): Int = {
if (n == 0) f else factorialTailRec(n - 1, n * f)
}
factorialTailRec(n, 1)
}
for(i <-1 to ITERS) println("factorialTailRec(" + i + ") = " + factorialTailRec(i))
def factorial(n:Int) : Int = {
if(n == 0) 1 else n * factorial(n-1)
}
for(i <-1 to ITERS) println("factorial(" + i + ") = " + factorial(i))
}
Observe that the inner tailRec function calls the second argument by name. for which the #tailRec annotation still does NOT throw a compile-time error!
I've been playing around with different values for the ITERS variable, and for a value of 100,000, I receive a... StackOverflowError!
(The result of zero is there because of overflow of Int.)
So I went ahead and changed the signature of factorialTailRec/2, to:
def factorialTailRec(n: Int, f: Int): Int
i.e call by value for the argument f. This time, the portion of main that runs factorialTailRec finishes absolutely fine, whereas, of course, factorial/1 crashes at the exact same integer.
Very, very interesting. It seems as if call by name in this situation maintains the stack frames because of the need of computation of the products themselves all the way back to the call chain.
Trying to solve the exercises in the book "Scala for the Impatient", I have a little problem. (Below are my solutions)
1: Write a for loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 825152896
var p = 1; val S = "Hello"
for (i <- S) p*= i
println(p)
2: Solve the preceding exercise without writing a loop. (Hint: look at the String0ps Scaladoc.)
val St="Hello".map(_.toInt).product ; println(St)
3: Write a function product(s : String) that computes the product, as described in the preceding exercises.
def product(s: String)={
val S=s; println(S.map(_.toInt).product)
}
product("Hello")
Make the function of the preceding exercise a recursive function.
??? I do not know how to do it
I hope that someone can help me.
Best regards,
Francesco
Using well-known recursive functions and modifying them to comply with a different problem may prove quite a helpful approach.
Consider as a start-up pattern the factorial recursive function,
def factorial(n: Int): Int =
if (n <= 1) 1 else n * factorial (n-1)
Consider now the factorial recursive function where the input is assumed to be a list of integers from 1 to n, and so note the way the input list is reduced to the base case,
def factorial(xs: List[Int]): Int =
if (xs.isEmpty) 1 else xs.head * factorial (xs.tail)
This transformation is now closer to a solution for the original problem on string input.
Ok...finally my code works:
def prodRec(s: String): Int = {
if (s.toList.isEmpty) 1
else {
s.toList.head * prodRec(s.tail)
}
}
println(prodRec("Hello"))
I hope that this code snippet might help someone else...
best regards
francesco
Here is another way of writing the recursive solution to the product:
def getProduct(s: String):Int = {
def accumulate(acc:Int,ch:Array[Char]):Int = {
ch.headOption match {
case None => acc
case Some(x) => accumulate(acc*x.toInt,ch.tail)
}
}
accumulate(1,s.toArray)
}
Maybe I solved with:
def prodRec(s: String): Int = {
var s2 =s.toList
if (s2.isEmpty) 1
else {
s2.head * prodRec (s.tail)
}
}
My variant of tail recursive function. No vars used, which is a plus.
def product(s: String): Unit = {
#tailrec
def help(z: Long, array: Array[Char]): Long = {
if (array.isEmpty) z else help(z * array.head.toInt, array.tail)
}
print(help(1L, s.toCharArray))
}
def product (s:String): Long ={
if (s.length==1) s(0) else s.head * s.product (s.tail)
}
I have a lazily-calculated sequence of objects, where the lazy calculation depends only on the index (not the previous items) and some constant parameters (p:Bar below). I'm currently using a Stream, however computing the stream.init is typically wasteful.
However, I really like that using Stream[Foo] = ... gets me out of implementing a cache, and has very light declaration syntax while still providing all the sugar (like stream(n) gets element n). Then again, I could just be using the wrong declaration:
class FooSrcCache(p:Bar) {
val src : Stream[FooSrc] = {
def error() : FooSrc = FooSrc(0,p)
def loop(i: Int): Stream[FooSrc] = {
FooSrc(i,p) #:: loop(i + 1)
}
error() #:: loop(1)
}
def apply(max: Int) = src(max)
}
Is there a Stream-comparable base Scala class, that is indexed instead of linear?
PagedSeq should do the job for you:
class FooSrcCache(p:Bar) {
private def fill(buf: Array[FooSrc], start: Int, end: Int) = {
for (i <- start until end) {
buf(i) = FooSrc(i,p)
}
end - start
}
val src = new PagedSeq[FooSrc](fill _)
def apply(max: Int) = src(max)
}
Note that this might calculate FooSrc with higher indices than you requested.
I was looking at solving a very simple problem, Eratosthenes sieve, using idiomatic Scala, for learning purposes.
I've learned a Stream caches, so it is not so performant when determining the nth element because it's an O(n) complexity access with memoisation of data, therefore not suitable for this situation.
def primes(nums: Stream[Int]): Stream[Int] = {
Stream.cons(nums.head,
primes((nums tail) filter (x => x % nums.head != 0)))
}
def ints(n: Int): Stream[Int] = {
Stream.cons(n, ints(n + 1))
};
def nthPrime(n: Int): Int = {
val prim = primes(ints(2)).view take n toList;
return prim(n - 1);
};
The Integer stream is the problematic one. While the prime number filtering is done, JVM runs OutOfMemory. What is the correct way to achieve the same functionality without using Streams?
Basically take a view of primes from a view of ints and display the last element, without memoisation?
I have had similar cases where a stream was a good idea, but I did not need to store it's values. In order to consume the stream without storing it's values I created (what I called) ThrowAwayIterator:
class ThrowAwayIterator[T](var stream: Stream[T]) extends Iterator[T] {
def hasNext: Boolean = stream.nonEmpty
def next(): T = {
val next = stream.head
stream = stream.tail
next
}
}
Make sure that you do not store a reference to the instance of stream that is passed in.
I m trying to learn scala these days.
I get confused with _ operator.
How can I use it in the following program ?
Also how this program can be made more concise ?
I have learnt that scala promotes the use of val over var, in this case how can we use val for balance ?
private object Main {
def main(args: Array[String]): Unit = {
val acc1 = new PiggyBank(5)
acc1.printBalance
acc1 deposit 5
acc1.printBalance
acc1 withdraw 5
acc1.printBalance
}
}
private class PiggyBank(open_Bal: Int) {
var balance = open_Bal
def deposit(value: Int) = balance = balance + value
def printBalance = println(balance)
def iswithdrawable(value: Int) = balance >= value
def withdraw(value: Int) = {
if (iswithdrawable(value)) {
balance = balance - value
}
}
}
Thanks in Advance :)
You're probably going to get a million answers here :) But, based on the content of your question, you need to read a book. I'd recommend Programming in Scala 2nd Edition. I've read it twice and it's gotten dog-eared and coffee stained in the process.
The reason I say this is because Scala presents you with a new paradigm, and you're writing Java code in Scala. This is perfectly fine for starters but you're not going to learn what you want to learn that way. The book is a great start that will give you the foundation to learn more.
For example, here's what I'd change in your code:
case class PiggyBank(balance: Double) {
def deposit(amount: Double) = PiggyBank(balance + amount)
def withdraw(amount: Double): Option[PiggyBank] = {
if (balance >= amount) Some(PiggyBank(balance - amount))
else None
}
override def toString() = balance.toString
}
But "why" I would want to do it that way is the real question, and it's that question that you really need to have answered, I argue. In a nutshell, it's immutable and a bit more functional (although, this is a toy example and there's tons of room for improvement here), but why is it and why do we care? Books answer this stuff.
Given that, you can start to use the _ a bit if you want. For example:
val result = PiggyBank(500) withdraw 200 flatMap { _.withdraw(200) }
println(result.getOrElse(0))
But if you're like most noobs (like me a long while ago), you're going to ask "Why on earth is that better??". That's not an answer you're going to find in a quick SO post. I could go on and on and on and on but the bottom line is that there are books out there that have already done that, and have done that better than I can.
There is no need for _ here. _ is not an operator, but a placeholder for parameters in closures. E.g. when you call a foldLeft an a collection of integers to you sum them up you could write List(1,2,3,4).foldLeft(0)(_ + _) instead of List(1,2,3,4).foldLeft(0)((x,y) => x + y). The first _ will be the x in the second example and the second _ the y.
You would use val with immutable objects. Since your PiggyBank is mutable, you need var for the mutable internal state.
You could turn your PiggyBank in immutable this way (basically creating a new immutable object each operation that would change the state of the object):
class PiggyBank(val balance : Int) {
def deposit(value: Int) = new PiggyBank(balance + value)
def printBalance = println(balance)
def iswithdrawable(value: Int) = balance >= value
def withdraw(value: Int) = if (iswithdrawable(value)) new PiggyBank(balance - value) else this;
}
So you could write this:
object Main {
def main(args: Array[String]): Unit = {
val acc1 = new PiggyBank(5) deposit 5 withdraw 5
acc1.printBalance
}
Regarding underscore/wildcards, these are helpful reads, "_" is frequently encountered in idiomatic code:
http://www.slideshare.net/normation/scala-dreaded
http://agileskills2.org/blog/2011/05/01/revealing-the-scala-magicians-code-expression/
Book index for Staircase vers. 2 has 7 entries for "_":
"curried functions", "existential types", "function literals",
"in identifiers" "import statements" "match expressions" and "initialize field to default value"
http://www.artima.com/pins1ed/book-index.html#indexanchor
very telling comment: underscore as a wildcard at both the term and type level plus as a way to coerce a method into a first class function.
http://lambda-the-ultimate.org/node/2808#comment-41717