# Foldl returns a tuple in SML?

The problem I am working on is to take a list of integers and return the average of those numbers. It must conform to a specific format that looks like this:

fun average (n::ns) =
let
val (a,b) = fold? (?) ? ?
in
real(a) / real(b)
end;

I am allowed to replace question marks and not use any built-in functions. I have a working solution, but it doesn't follow these guidelines.

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 the fold function return a tuple? Something like this is what I want it to be done, but obviously I can't do it ...

val (a,b) = ((foldl (fn(x, y)=>(x+y), count++) n ns)

+3

source to share

The return type foldl

is the type of the original counter. So the idea is to provide a tuple including the sum and number of items in the list:

fun average (n::ns) =
let
val (a, b) = foldl (fn (x, (sum, count)) => (sum+x, count+1)) (n, 1) ns
in
real(a) / real(b)
end

Note that your solution fails if the list is empty, it is better to add another case of handling an empty list (either return 0.0 or throw a custom exception):

fun average [] = 0.0
| average (n::ns) = (* the same as above *)

+4

source

All Articles