[Raku] 如何定義函式

``````sub example ( 特徵宣告 ) {
本文
}``````

``````參數串列 --> 傳回值
``````

``變數 = example( 參數串列 );``

例：華氏溫度換攝氏溫度

``````C = (F - 32) / 1.8
``````

``````sub celsius-from-farenheit (Rat \$f --> Rat) {
return (\$f - 32) / 1.8;
}``````

``````sub farenheit-from-celsius (Rat \$c --> Rat) {
return 1.8 * \$c + 32;
}``````

例：BMI 值計算

BMI (身體質量指數) 的計算公式為：

``````BMI = 體重 / 身高²
``````

``````(Rat \$weight, Rat \$height --> Rat)
``````

``````sub bmi (Rat \$weight, Rat \$height --> Rat) {
return \$weight / \$height ** 2;
}``````

例：空氣品質指標數字轉口語敘述

``````sub airquality-in-zh-Hant-TW (Int \$x --> Str) {
本文
}``````

``(Int \$x where { 0 <= \$x <= 500 } --> Str)``

``````sub airquality-in-zh-Hant-TW (Int \$x where { 0 <= \$x <= 500 } --> Str) {
return do {
if 0 <= \$x <= 50       { "良好" }
elsif 51 <= \$x <= 100  { "普通" }
elsif 101 <= \$x <= 150 { "對敏感族群不健康" }
elsif 151 <= \$x <= 200 { "對所有族群不健康" }
elsif 201 <= \$x <= 300 { "非常不健康" }
elsif 301 <= \$x <= 500 { "危害" }
};
}``````

``````sub airquality-in-zh-Hant-TW (Int \$x where { 0 <= \$x <= 500 } --> Str) {
return do {
given \$x {
when 0..50    { "良好" }
when 51..100  { "普通" }
when 101..150 { "對敏感族群不健康" }
when 151..200 { "對所有族群不健康" }
when 201..300 { "非常不健康" }
when 300..500 { "危害" }
}
};
}``````

``````sub airquality-in-zh-Hant-TW (Int \$x where { 0 <= \$x <= 500 } --> Str) {
my constant @translations = [
"良好",
"普通",
"對敏感族群不健康",
"對所有族群不健康",
"非常不健康",
"非常不健康",
"危害",
"危害",
"危害",
"危害",
];

return @translations[ \$x div 50 ];
}``````

例：同時取得商數及餘數的整數除法

``````(Int \$dividend, Int \$divisor --> Array[Int])
``````

`\$divident` 為被除數，`\$divisor` 為除數。傳回值為兩個整數，分別代表商數及餘數。在此先簡單以 `Array[Int]` 做為傳回值的型別。

``````sub divmod (Int \$dividend, Int \$divisor --> Array[Int]) {
my \$quotient = \$dividend div \$divisor;
my \$remainder = \$dividend % \$divisor;

return Array[Int].new( \$quotient, \$remainder );
}``````

``````my (\$q, \$r) = divmod(14, 3);

say \$q; #=> 4
say \$r; #=> 2``````

``````sub infix:<divmod> (Int \$dividend, Int \$divisor --> Array[Int]) {
my \$quotient = \$dividend div \$divisor;
my \$remainder = \$dividend % \$divisor;
return Array[Int].new( \$quotient, \$remainder );
}

my (\$q, \$r) = 14 divmod 3;

say \$q; #=> 4
say \$r; #=> 2``````