#2791 List average error

small_petit Wed 13 May 2020

Hello, can I please get any help from the forum why this block of code does not compile? I am trying to find the average of Float values in a list.

Float average(Float[] list)
{
sum := list.reduce(0.0f) |Float r, Float v -> Float| { r + v }
return sum / list.size
}

Also, why does Fantom not have methods like product and sum in the calls for List?

Thank you

SlimerDude Wed 13 May 2020

Hi small_petit,

Fantom's generics are pretty limited so List.reduce() just returns Obj for all cases, and Obj doesn't have a divide method!

To get round it, just cast the result to a Float:

sum := (Float) list.reduce(0.0f) |Float r, Float v -> Float| { r + v }
return sum / list.size

Product and sum are only useful for numeric types, whereas Lists may hold items of any type (not just numerics).

small_petit Wed 13 May 2020

Thank you SlimerDude. Clearly understood. Regards.

Login or Signup to reply.