Open main menu

CDOT Wiki β

GPU621/Chapel

Revision as of 23:05, 29 November 2022 by Lhuangtang (talk | contribs) (Overloading)

Introduction

The Chapel is an open-source programming language designed for productive parallel computing at scale. The Chapel compiler is written in C and C++14. The backend is LLVM, written in C++. The goal of Chapel is to improve the programmability of parallel computers in general.

Installation

Basic

Variables

Variables are declared with the var keyword. Variable declarations must have a type, initializer, or both.

     var myVariable1: int;
     writeln("myVariable1 = ", myVariable1);

const and param can be used to declare runtime constants and compile-time constants respectively. A const must be initialized in place, but can have its value generated at runtime. A param must be known at compile time.

     const myConst: real = sqrt(myVariable2);
     param myParam = 3.14;
     writeln("myConst = ", myConst, ", myParam = ", myParam);

At module scope, all three variable kinds can be qualified by the config keyword. This allows the initial value to be overridden on the command line. A config var or config const may be overridden when the program is executed; a config param may be overridden when the program is compiled. Similarly, type aliases maybe be qualified by the config keyword. The comment following each declaration shows how the value can be modified.

     config var cfgVar = "hello";         // ./variables --cfgVar="world"
     config const cfgConst: bool = false; // ./variables --cfgConst=true
     config param cfgParam = 4;           // chpl variables.chpl -s cfgParam=1
     config type cfgType = complex;       // chpl variables.chpl -s cfgType=imag
     writeln("cfgVar = ", cfgVar,
             ", cfgConst = ", cfgConst,
             ", cfgParam = ", cfgParam,
             ", cfgType = ", cfgType:string);

Procedure

The primer covers procedures including overloading, argument intents and dynamic dispatch.

Overloading

The prime allows the user to do the overload function.

   proc factorial(x: int) : int
   {
     if x < 0 then
       halt("factorial -- Sorry, this is not the gamma procedure!");
     return if x == 0 then 1 else x * factorial(x-1);
   }

We can overload the factorial function to accept the 32-bit integers.

   proc factorial(x: int(32)) : int(32)
   {
     if x < 1 then
       halt("factorial -- Invalid operand.");
     if x < 3 then return x;
     return x * (x-1) * factorial(x-2);

}

Reference