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(n: Int) = if (n > 0) 1 else if (n == 0) 0 else -1
scala> def signum(n: Int) = if (n > 0) 1 else if (n == 0) 0 else -1
signum: (n: Int)Int
scala> signum(1)
res30: Int = 1
scala> signum(5)
res31: Int = 1
scala> signum(-1)
res32: Int = -1
scala> signum(0)
res33: Int = 0
2. What is the value of an empty block expression {}? What is its type?
type: Unit, value: ()
Unit
is a subtype of [[scala.AnyVal]]. There is only one value of typeUnit
,()
from Scala Doc
val a: Unit = {}
3. Come up with one situation where the assignment x = y = 1
is valid in Scala. (Hint: Pick a suitable type for x.)
scala> var x = {}
x: Unit = ()
scala> var y = 1
y: Int = 1
scala> x = y = 1
x: Unit = ()
4. Write a Scala equivalent for the Java loop
scala> for (i <- 10.to(0, -1)) println(i)
10
9
8
7
6
5
4
3
2
1
0
scala> for (i <- 0.to(10).reverse) println(i)
10
9
8
7
6
5
4
3
2
1
0
5. Write a procedure countdown(n: Int)
that prints the numbers from n
to 0.
scala> def countdown(n: Int) = for (i <- 0 to n reverse) println(i)
warning: there was one feature warning; re-run with -feature for details
countdown: (n: Int)Unit
scala> countdown(5)
5
4
3
2
1
0
不知道这样写为什么会有warning
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 9415087488L
.
scala> var product = 1L
product: Long = 1
scala> for (c <- "Hello") product *= c.toLong
scala> product
res22: Long = 9415087488
7. Solve the preceding exercise without writing a loop. (Hint: Look at the Stringops
Scaladoc.)
没看懂要求。
scala> "Hello".foldLeft(1L)((product: Long, char: Char) => product * char)
res19: Long = 9415087488
8. Write a function product(s: String)
that computes the product, as described in the preceding exercises.
scala> def product(s: String) : Long = s.foldLeft(1L)((product, char) => product * char.toLong)
product: (s: String)Long
scala> product("Hello")
res29: Long = 9415087488
9. Make the function of the preceding exercise a recursive function.
def product(s: String) : Long = {
if (s.length == 0)
0
else if (s.length == 1)
s(0).toLong
else
s(0) * product(s.drop(1))
}
10. Write a function that computes xn , where n is an integer. Use the following recursive definition:
-
xn=y2
if
n
is even and positive, where
y=xn/2 - xn=x∗xn−1 if n is odd and positive.
x0=1 .- xn=1/x−n if n <script type="math/tex" id="MathJax-Element-9">n</script> is negative.
def pow(x: Double, n: Int) : Double = {
if (n == 0)
1
else if (n > 0 && n % 2 == 0) {
val tmp = pow(x, n / 2)
tmp * tmp
}
else if (n > 0 && n % 2 == 1)
pow(x, n - 1) * x
else
1 / pow(x, -n)
}