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?
product
sum
Thank you
Hi small_petit,
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!
List.reduce()
Obj
To get round it, just cast the result to a Float:
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).
Thank you SlimerDude. Clearly understood. Regards.
SlimerDude
Login or Signup to reply.
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.
Also, why does Fantom not have methods like
product
andsum
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 returnsObj
for all cases, andObj
doesn't have a divide method!To get round it, just cast the result to a
Float
: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.