Skip to content

Commit

Permalink
Intro exercises
Browse files Browse the repository at this point in the history
Formatting
  • Loading branch information
mattvenz committed Oct 10, 2023
1 parent 3ee27a0 commit 51e277c
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions src/main/scala/introcourse/level01/IntroExercises.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,24 @@ object IntroExercises {
* and can be inferred by the compiler.
* scala> add(1, 2)
* > 3
**/
def add(x: Int, y: Int): Int = ???

*/
def add(x: Int, y: Int): Int = x + y

/**
* Let's write the curried version of the `add` function defined previously
* scala> addCurried(1)(2)
* > 3
**/
def addCurried(x: Int)(y: Int): Int = ???

*/
def addCurried(x: Int)(y: Int): Int = x + y

/**
* Reuse the `addCurried` function and partially apply it for adding 5 to anything.
* scala> add5(4)
* > 9
*
**/
*/
def add5(x: Int): Int = {
val f: Int => Int = ???
???
val f: Int => Int = addCurried(5)
f(x)
}

/**
Expand All @@ -46,12 +43,12 @@ object IntroExercises {
* How many ways can you implement this function?
* Note: Square brackets (Types at compile time), round brackets (Values at run time)
*/
def foo[A](a: A): A = ???
def foo[A](a: A): A = a

/**
* How about this one?
*/
def bar(a: Int): Int = ???
def bar(a: Int): Int = 1000

/**
* What does the return type of this function tell us about
Expand All @@ -67,22 +64,25 @@ object IntroExercises {
*
* Important: Every `if` must have an `else`! Otherwise your function is not total.
*/
def timesTwoIfEven(x: Int): Int = ???
def timesTwoIfEven(x: Int): Int = {
if (x % 2 == 0) x * 2
else x
}

/**
* scala> showNumber(100)
* > "The number is 100"
*
* Hint: Use string interpolation, e.g. s"$x"
*/
def showNumber(x: Int): String = ???
def showNumber(x: Int): String = s"The number is $x"

/**
* Tuples
*
* How can we group together `name` and `age` in a pair?
*/
def pair(name: String, age: Int): (String, Int) = ???
def pair(name: String, age: Int): (String, Int) = (name, age)

/**
* How can we extract the first element of a pair?
Expand All @@ -92,11 +92,17 @@ object IntroExercises {
*
* https://docs.scala-lang.org/tour/tuples.html
*/
def first(pair: (String, Int)): String = ???
def first(pair: (String, Int)): String = {
val (name, _) = pair
name
}

/**
* How can we extract the second element of a pair?
*/
def second(pair: (String, Int)): Int = ???

def second(pair: (String, Int)): Int = {
pair match {
case (_, age) => age
}
}
}

0 comments on commit 51e277c

Please sign in to comment.