diff --git a/src/main/scala/introcourse/level01/IntroExercises.scala b/src/main/scala/introcourse/level01/IntroExercises.scala index 444f5664..027c38ec 100644 --- a/src/main/scala/introcourse/level01/IntroExercises.scala +++ b/src/main/scala/introcourse/level01/IntroExercises.scala @@ -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) } /** @@ -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 @@ -67,7 +64,10 @@ 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) @@ -75,14 +75,14 @@ object IntroExercises { * * 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? @@ -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 + } + } }