Created
May 31, 2012 19:01
-
-
Save yashk/2845460 to your computer and use it in GitHub Desktop.
scala for impatient exercise chapter 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prob 6 result has overflown. Do you want to try BigInt?
L32: maybe var prod: BigInt = 1 ?