In trying to write an arithmetic mean function, it is perhaps better to write one template function rather than two type specific functions. One can write:
proc mean(data: [?] ?T): real
but how to restrict T to being int or real.
Also is it possible to define an array that can have either int or real data, i.e. is there a way of expressing union types for array contents?
To restrict the type of T to int or real types of any size you can add a where clause to the function definition:
proc mean(data: [] ?T): real where isIntType(T) || isRealType(T) { ... }
The isIntType and isRealType functions are defined in the Types module: http://chapel.cray.com/docs/latest/modules/standard/Types.html
Chapel supports safe unions and arrays of unions. Unions are described in section 17 of the Chapel language specification: http://chapel.cray.com/docs/latest/_downloads/chapelLanguageSpec.pdf
union IntOrReal {
var i: int;
var r: real;
}
var intRealArray: [1..2] IntOrReal;
intRealArray[1].i = 1;
intRealArray[2].r = 2.0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With