Adaの日本語情報を増やす(1)
Ada勉強メモ。結構予想外のところも。
constant
Adaのconstantが一定なのは1回のprocedureが終了するまで。同じprocedureでも、次に呼ばれるときには違う定数となってることもある。
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Calendar; use Ada.Calendar;
procedure Test is
function Random return Integer is -- 現在時刻を元に擬似乱数を返す関数
begin
return Integer(Seconds(Clock));
end Random;
procedure Const_Test is
X : constant Integer := Random; -- 定数を宣言、値はランダムな値を返す関数から取得
begin
Put(X); -- 出力
end Const_Test;
begin
Const_Test; -- 1回目
delay Duration(3); -- 乱数が変化するのを3秒待つ(笑
Const_Test; -- 2回目
end Test;
-- 63030 63033
-- 定数が変化しているのがわかる
case
ほかの言語と違い、変数の型が持つrange内の全可能性をwhenすることが強制される。IntegerならInteger'FastからInteger'Lastまで全範囲。
めんどくさい場合はwhen othersで逃れられる。
declare
局所変数用。宣言部が乱雑になるのを防ぐことができる。
declare
Temp : Foo;
begin
Temp := .....;
end;
remとmod
Adaには余剰が2種類有る。符号の扱いが変わる。
rem- 被除数(左辺)と同じ符号
mod- 除数(右辺)と同じ符号
and thenとand
どちらも論理演算子。左辺がFALSEだった際の動作が違う。
and then- 左辺がFLASEなら右辺は実行しない(Cと同じ)
and- 左辺がFLASでも、必ず右辺を実行
in
I in 1 .. 5
Iが1, 2, 3, 4, 5のいずれかならTRUE
数値宣言
特定の型に属さない数値定数。
type Foo is range Integer'First .. Integer'Last -- Integerとは違う型!
C_Foo : constance Foo = 10
C_Integer : constance Integer = 20
C_Num : constance = 30;
X : Foo;
Y : Ineter;
X := C_Foo; -- OK
X := C_Integer; -- ERROR
X := C_Num; -- OK
Y := C_Foo; -- ERROR
Y := C_Integer; -- OK
Y := C_Num; -- OK
in
列挙型を順番に処理する
with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
type Enum is (Foo, Bar, Baz);
begin
for I in Enum loop
Put_Line(Enum'Image(I));
end loop;
end Test;
-- Foo
-- Bar
-- Baz
revese
for I in reverse Enumとかけば、列挙型を逆順にイテレートできる。