Skip to content

Instantly share code, notes, and snippets.

@frank-leap
Created April 25, 2015 09:45
Show Gist options
  • Save frank-leap/24c6869cbd3ed2e61ed5 to your computer and use it in GitHub Desktop.
Save frank-leap/24c6869cbd3ed2e61ed5 to your computer and use it in GitHub Desktop.
s4di - Chapter 2 - Exercises
package chapter2
import math._
object ExercisesCh2 {
def signum(i: Int) = if (i < 0) -1 else if (i > 0) 1 else 0
//> signum: (i: Int)Int
signum(5) //> res0: Int = 1
signum(-5) //> res1: Int = -1
signum(0) //> res2: Int = 0
{}
var x = () //> x : Unit = ()
var y = 0 //> y : Int = 0
x = y = 1
def countdown(n: Int) { for (i <- n to 0 by -1) println(i) }
//> countdown: (n: Int)Unit
countdown(5) //> 5
//| 4
//| 3
//| 2
//| 1
//| 0
def prodUnicode(s: String) = {
var total: Long = 1
for (c <- s) total *= c
total
} //> prodUnicode: (s: String)Long
prodUnicode("Hello") //> res3: Long = 9415087488
val total = "Hello".foldLeft(1L)(_ * _.toInt) //> total : Long = 9415087488
def prodUnicodeRec(s: String): Long = {
val tail = s.tail
s.head.toLong * (if (tail.size == 0) 1 else prodUnicodeRec(s.tail))
} //> prodUnicodeRec: (s: String)Long
prodUnicodeRec("Hello") //> res4: Long = 9415087488
def computePow(x: Double, n: Int): Double = {
if (n == 0) 1
else if (n < 0) 1 / computePow(x, -n)
else if (n % 2 == 0) pow(computePow(x, n / 2), 2)
else x * computePow(x, n - 1)
} //> computePow: (x: Double, n: Int)Double
computePow(2, 0) //> res5: Double = 1.0
computePow(2, -1) //> res6: Double = 0.5
computePow(2, 1) //> res7: Double = 2.0
computePow(2, 2) //> res8: Double = 4.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment