The problem I’m working on needs to take in a list of integers and return the average of those numbers. It needs to fit a specific format that looks like this…
fun average (n::ns) =
let
val (a,b) = fold? (?) ? ?
in
real(a) / real(b)
end;
I’m only allowed to replace the question marks and cannot used any built in functions. I have a working solution, but it doesn’t adhere to these rules.
fun average (n::ns) =
let
val (a,b) = ((foldl (fn(x, y)=>(x+y)) n ns), length(ns)+1)
in
real(a) / real(b)
end;
So, is there a way to make a fold function return a tuple? Something like this is what I want it to do, but obviously I can’t do this…
val (a,b) = ((foldl (fn(x, y)=>(x+y), count++) n ns)
Return type of
foldlis the type of the initial accummulator. So the idea here is to provide a tuple including sum and count of elements in the list:Notice that your solution fails if the list is empty, it’s better to add another case of handling empty list (either returning 0.0 or throwing a custom exception):