Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
|
pp:2024:scala:l02 [2024/03/08 18:37] robert.stoica2205 created |
pp:2024:scala:l02 [2025/03/05 10:47] (current) pdmatei |
||
|---|---|---|---|
| Line 18: | Line 18: | ||
| <code scala> | <code scala> | ||
| def doubler(): Int => Int = { | def doubler(): Int => Int = { | ||
| + | ??? | ||
| + | } | ||
| + | </code> | ||
| + | |||
| + | **2.1.3** Create a function ''trycatch'' that takes an integer and evaluates its value using the try function. If an error occurs (try function returns 0), the catch function will be called instead. | ||
| + | <code scala> | ||
| + | def trycatch(t: Int => Int, c: Int => Int)(x: Int): Int = { | ||
| + | ??? | ||
| + | } | ||
| + | </code> | ||
| + | |||
| + | **2.1.4** Write a function ''realtrycatch'' where t and c take no parameters and produce a result upon evaluation. If an error occurs (try function returns 0), the catch function will be called instead. | ||
| + | <code scala> | ||
| + | def realtrycatch(t : => Int, c: => Int): Int = { | ||
| ??? | ??? | ||
| } | } | ||
| Line 23: | Line 37: | ||
| ===== 2.2 Custom high order functions ===== | ===== 2.2 Custom high order functions ===== | ||
| + | |||
| **2.2.1** Define the function ''foldWith'' which uses an operation ''op'' to reduce a range of integers to a value. For instance, given that ''op'' is addition (+), the result of folding the range 1 to 3 will be 1+2+3=6. ''foldWith'' should be curried (it will take the operation and return another function which expects the bounds). | **2.2.1** Define the function ''foldWith'' which uses an operation ''op'' to reduce a range of integers to a value. For instance, given that ''op'' is addition (+), the result of folding the range 1 to 3 will be 1+2+3=6. ''foldWith'' should be curried (it will take the operation and return another function which expects the bounds). | ||
| <code scala> | <code scala> | ||
| Line 31: | Line 46: | ||
| </code> | </code> | ||
| - | **2.2.2** Define the function ''foldConditional'' which extends ''foldWith'' by also adding a predicate ''p: Int => Int''. ''foldConditional'' will reduce only those elements of a range which satisfy the predicate. | + | **2.2.2** Define the function ''foldConditional'' which extends ''foldWith'' by also adding a predicate ''p: Int => Boolean''. ''foldConditional'' will reduce only those elements of a range which satisfy the predicate. |
| <code scala> | <code scala> | ||
| Line 53: | Line 68: | ||
| def compare(x: Int, y: Int, z: Int): Int = | def compare(x: Int, y: Int, z: Int): Int = | ||
| { | { | ||
| - | if x > y && x > z then | + | if (x > y && x > z) x |
| - | x | + | else if (y > x && y > z) y |
| - | else if y > x && y > z then | + | else z |
| - | y | + | |
| - | else | + | |
| - | z | + | |
| } | } | ||
| </code> | </code> | ||