Skip to content

Instantly share code, notes, and snippets.

@weldpua2008
Last active March 2, 2019 07:53
Show Gist options
  • Save weldpua2008/892ee59b5918b2f37d5677e4211e0f74 to your computer and use it in GitHub Desktop.
Save weldpua2008/892ee59b5918b2f37d5677e4211e0f74 to your computer and use it in GitHub Desktop.
// Random ASCII
def randomString(length: Int) = scala.util.Random.alphanumeric.take(length).mkString
//signum
def signum[T: Numeric](v: T) : Int = {
val v1 = implicitly[Numeric[T]].toLong(v)
if(v1 > 0 ) 1 else if(v1 < 0 ) -1 else 0
}
print(signum(1.2))
print(signum(BigInt(2).pow(1029)))
/**
* Come up with one situation where the assignment x = y = 1 is valid in Scala.
* (Hint: Pick a suitable type for x.)
*/
// #1
var y = 2
var x = y = 1
// #2
var x:Unit = {}
var y = 0
x = y = 1
/**
* Write a Scala equivalent for the Java loop
* for (int i = 10; i >= 0; i--) System.out.println(i);
*/
for (i<- (0 to 10).reverse) println(i)
for (i <- 10.to(0, -1)) println(i)
(0 to 10).reverse.foreach(println)
def countdown(n: Int): Unit ={
for(i<- (0 to n).reverse) println(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment