-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Andreas Roehler <[email protected]>
- Loading branch information
1 parent
e914f2d
commit 1cd1ac9
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |