Skip to content

Instantly share code, notes, and snippets.

@yashk
Created May 31, 2012 19:01
Show Gist options
  • Save yashk/2845460 to your computer and use it in GitHub Desktop.
Save yashk/2845460 to your computer and use it in GitHub Desktop.
scala for impatient exercise chapter 2
/*1. The signum of a number is 1 if the number is positive, –1 if it is negative, and
0 if it is zero. Write a function that computes this value.
*/
def signum(x: Int): Int = if(x>0) 1 else -1
/*
4. Write a Scala equivalent for the Java loop
for (int i = 10; i >= 0; i--) System.out.println(i);
*/
for(i <- 10.to(0,-1)) println(i)
/*
5. Write a procedure countdown(n: Int) that prints the numbers from n to 0.
*/
def countDown(n: Int): Unit= if(n == 0) println(0) else if(n>0) {println(n);countDown(n-1)}
/*
6. 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 prod =0
for(c <- "Hello") prod*=c.toInt
/*
7. Solve the preceding exercise without writing a loop. (Hint: Look at the StringOps
Scaladoc.)
*/
var prod =0
"Hello".foreach(prod*=_.toInt)
8. Write a function product(s : String) that computes the product, as described
in the preceding exercises.
def product(s:String) :Int = {
var prod =1
s.foreach(prod*=_.toInt)
prod
}
/*
9. Make the function of the preceding exercise a recursive function.
*/
def prodR(s:String):Int = {
if(s.length() == 1) s.head.toInt
else s.head.toInt * prodR(s.drop(1))
}
@yuchsiao
Copy link

yuchsiao commented Apr 3, 2016

Prob 6 result has overflown. Do you want to try BigInt?

L32: maybe var prod: BigInt = 1 ?

@WangPengGG
Copy link

var prod =0
should be
var prod = 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment