Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Last active June 15, 2025 03:59
Show Gist options
  • Select an option

  • Save hhimanshu/55564b70dac97d0aa4eb to your computer and use it in GitHub Desktop.

Select an option

Save hhimanshu/55564b70dac97d0aa4eb to your computer and use it in GitHub Desktop.
Scala for the Impatient Exercises

This gist will contain all the exercises from the book

/**
* 2. In the Scala REPL, compute the square root of 3, and then square that value. By how much does the result differ from 3? (Hint: The res variables are your friend.)
*/
scala> math.sqrt(3)
res1: Double = 1.7320508075688772
scala> res1*res1
res2: Double = 2.9999999999999996
scala> 3 - res2
res3: Double = 4.440892098500626E-16
// 3. Are the res variables val or var?
scala> res1 = 3
<console>:11: error: reassignment to val
res1 = 3
^
/**
* 4. Scala lets you multiply a string with a number—try out "crazy" * 3 in the REPL.
* What does this operation do? Where can you find it in Scaladoc?
*/
// StringOps.* : Return the current string concatenated n times.
scala> "crazy "*3
res6: String = "crazy crazy crazy "
/**
* 5. What does 10 max 2 mean? In which class is the max method defined?
*/
// Int.max: Returns this if this > that or that otherwise.
scala> 10 max 2
res7: Int = 10
scala> 10.max(2)
res8: Int = 10
/**
* 6. Using BigInt, compute 21024.
*/
scala> BigInt(2) pow 1024
res13: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
/**
* 7. What do you need to import so that you can get a random prime as probablePrime(100, Random),
* without any qualifiers before probablePrime and Random?
*/
scala> import scala.util.Random
import scala.util.Random
scala> import scala.math.BigInt
import scala.math.BigInt
scala> import scala.math.BigInt.probablePrime
import scala.math.BigInt.probablePrime
scala> probablePrime(100, Random)
res14: scala.math.BigInt = 931669304734992063893063804797
/**
* 8. One way to create random file or directory names is to produce a random BigInt
* and convert it to base 36, yielding a string such as "qsnvbevtomcj38o06kul".
* Poke around Scaladoc to find a way of doing this in Scala.
*/
scala> probablePrime(100, Random) toString 36
res15: String = 2mojnrl2508jtnu26t01
/**
* 9. How do you get the first character of a string in Scala? The last character?
*/
scala> "Hello".head
res20: Char = H
scala> "Hello".last
res21: Char = o
/**
* 10. What do the take, drop, takeRight, and dropRight string functions do?
* What advantage or disadvantage do they have over using substring?
*/
// StringOps.drop: Selects all elements except first n ones.
// StringOps.dropRight: Selects all elements except last n ones.
// StringOps.take: Selects first n elements.
// StringOps.takeRight: Selects last n elements.
scala> "Hello World!" take 6
res22: String = "Hello "
scala> "Hello World!" drop 6
res23: String = World!
scala> "Hello World!" takeRight 6
res24: String = World!
scala> "Hello World!" dropRight 6
res25: String = "Hello "
/**
* 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.
*/
scala> def signum(num:Int) = if (num > 0) 1 else if (num < 0) -1 else 0
signum: (num: Int)Int
scala> signum(10)
res4: Int = 1
scala> signum(0)
res5: Int = 0
scala> signum(-123)
res6: Int = -1
/**
* 2. What is the value of an empty block expression {}? What is its type?
*/
// Value is 'no value' and type is Unit
scala> val empty = {}
empty: Unit = ()
scala> empty
/**
* 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: Any = _
x: Any = null
scala> var y: Int = _
y: Int = 0
scala> x = y = 1
x: Any = ()
scala> x
res0: Any = ()
scala> y
res1: Int = 1
/**
* 4. Write a Scala equivalent for the Java loop
* for (int i = 10; i >= 0; i--) System.out.println(i);
*/
// Range.by: Create a new range with the start and end values of this range and a new step.
scala> for(i<- 10 to 0 by -1) 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 <- n to 0 by -1) println(i)
countdown: (n: Int)Unit
scala> countdown(10)
10
9
8
7
6
5
4
3
2
1
0
/**
* 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.
*/
// IndexedSeq.product: Multiplies up the elements of this collection.
// returns
// the product of all elements in this sequence of numbers of type Int.
// Instead of Int, any other type T with an implicit Numeric[T] implementation can be used as element type of the sequence and as result type of product.
// Examples of such types are: Long, Float, Double, BigInt.
scala> (for(i <- "Hello") yield i.toLong).product
res19: Long = 9415087488
/**
* 7. Solve the preceding exercise without writing a loop. (Hint: Look at the StringOps Scaladoc.)
*/
scala> "Hello".map(c => c.toLong).product
res22: Long = 9415087488
/**
* 8. Write a function product(s : String) that computes the product, as described in the preceding exercises.
*/
scala> def product(s:String) = s.map(c => c.toLong).product
product: (s: String)Long
scala> product("Hello")
res23: Long = 9415087488
/**
* 9. Make the function of the preceding exercise a recursive function.
*/
scala> def product(s:String, p:Long):Long = s.isEmpty match {
| case false => product(s.tail, p * s.head.toLong)
| case true => p
| }
scala> def prod(s:String):Long = s.isEmpty match {
| case false => product(s, 1)
| case true => 0
| }
prod: (s: String)Long
scala> prod("")
res5: Long = 0
scala> prod("Hello")
res6: Long = 9415087488
/**
* 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 is negative.
* Don’t use a return statement.
*/
scala> def pow(x:Int, n:Int) = n match {
| case n if n > 0 && (n%2 == 0) => scala.math.pow(x, n/2)
| case n if n > 0 && (n%2 == 1) => x * scala.math.pow(x, n-1)
| case 0 => 1
| case n if n < 0 => 1/scala.math.pow(x, -n)
| }
pow: (x: Int, n: Int)Double
scala> pow(2, 4)
res0: Double = 4.0
scala> pow(2, 5)
res1: Double = 32.0
scala> pow(2, 0)
res2: Double = 1.0
scala> pow(2, -1)
res3: Double = 0.5
/**
* 1. Write a code snippet that sets a to an array of n random integers between 0 (inclusive) and n (exclusive)
*/
scala> def randomInRange(n:Int) = for(i <- 0 to n) yield Random.nextInt(n)
randomInRange: (n: Int)scala.collection.immutable.IndexedSeq[Int]
scala> randomInRange(100)
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(68, 47, 1, 20, 35, 93, 53, 24, 75, 46, 23, 61, 98, 62, 60, 38, 82, 69, 10, 82, 96, 30, 14, 50, 20, 42, 44, 11, 31, 18, 70, 13, 25, 77, 85, 89, 55, 45, 16, 44, 13, 50, 71, 58, 86, 16, 7, 79, 60, 31, 79, 52, 56, 86, 31, 85, 32, 84, 14, 54, 79, 56, 7, 68, 62, 87, 77, 4, 47, 28, 36, 23, 88, 19, 28, 41, 47, 3, 92, 88, 29, 22, 52, 8, 14, 76, 83, 45, 42, 45, 36, 77, 50, 12, 89, 28, 70, 97, 35, 70, 32)
/**
* 2. Write a loop that swaps adjacent elements of an array of integers. For example, Array(1, 2, 3, 4, 5) becomes Array(2, 1, 4, 3, 5).
*/
// http://stackoverflow.com/a/10160082/379235
scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)
scala> a.grouped(2).flatMap(_.reverse).toArray
res17: Array[Int] = Array(2, 1, 4, 3, 5)
/**
* 3. Repeat the preceding assignment, but produce a new array with the swapped values. Use for/yield.
*/
scala> (for {b <- a.grouped(2); c <- b.reverse} yield c).toArray
res16: Array[Int] = Array(2, 1, 4, 3, 5)
@B1llioner
Copy link

Пишу на питоне, ничо не понятно

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