📓Exercise: Implement functions with Ability operations
Using theStore
ability to keep track of aList
of numbers, write a function which takes in some numbern
ofNat
as an upper bound of a list from0
up to (but not including)n
and returns the average of the final list.
So, given an upper value of5
,the average produced would be the average of[0, 1, 2, 3, 4]
,or2.0
🔑Answer
🔑Answer
One possible solution is as follows:
averageOfRange : Nat ->{Store [Nat]} Float
averageOfRange : Nat ->{Store [Nat]} Float
averageOfRange n =
go = cases
i
| i Nat.== n ->
use Float /
use Nat toFloat
myList = Store.get
listSize = List.size myList
sum =
use Nat +
List.foldLeft (acc element -> element + acc) 0 myList
toFloat sum / toFloat listSize
| otherwise ->
use List +:
use Nat +
Store.modify (currentList -> i +: currentList)
go (i + 1)
go 0