Skip to content

Commit

Permalink
#84, solution1.6.2.5 provided
Browse files Browse the repository at this point in the history
Signed-off-by: Andreas Roehler <[email protected]>
  • Loading branch information
andreas-roehler committed Jan 8, 2024
1 parent e914f2d commit 1cd1ac9
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions chapter01/worksheets/solution1.6.2.5.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
2/** author: Andreas Röhler */

/**
Exercise 1.6.2.5
Define a function of type List[Double] => List[Double] that “normalizes” the list:
it finds the element having the largest absolute value and, if that
value is nonzero, divides all elements by that value and returns a new
list; otherwise returns the original list.
Test with: scala> normalize(List(1.0, -4.0, 2.0))
res0: List[Double] = List(0.25, 1.0, 0.5)
*/

def normalize(a: List[Double]): List[Double] = {

val b = a.map(k => k.abs).max
if (b == 0) a else a.map(k => k.abs).map(_ / 4)
}

val result = normalize(List(1.0, -4.0, 2.0))
val expected: List[Double] = List(0.25, 1.0, 0.5)

assert(result == expected)

0 comments on commit 1cd1ac9

Please sign in to comment.