Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the type signature of a template function in Chapel

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?

like image 591
Russel Winder Avatar asked Jan 22 '26 20:01

Russel Winder


1 Answers

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;
like image 149
David Iten Avatar answered Jan 25 '26 18:01

David Iten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!