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