![](/img/trans.png)
[英]How do I modify my post condition to achieve Gold standard of Spark proof - Ada SPARK
[英]How do I initialize a custom array type from the main file in Ada
我是一個 Ada 菜鳥,正在編寫一個簡單的 function,它采用整數列表並將每個元素遞減 1。我的青銅模式證明通過了,但嘗試實際使用 function,看看它是否真的在做它應該證明是一場斗爭。 我不確定如何初始化數組並分配值(應該是 0..10)。 我也不確定我是否可以只用一個遞減 function 而不是 decrement(integer) 和 decrementList(ArrayOfNumbers) 函數來實現這一點。 或者,如果我做得對。 任何幫助都是王牌,我沒有找到任何好的文檔,所以我覺得我應該猜測我的方式。 package 被稱為flip_coin,因為它是早期任務的一部分,任何與翻轉硬幣相關的事情都可以忽略!
這是規范文件:
package flip_coin with SPARK_Mode is
type Coin is (Heads, Tails);
type Index is range 0 .. 10;
type Numbers is array (Index) of Integer;
function flip (x : Coin) return Coin with
Post => flip'Result /= x;
procedure flipCoin (x : in out Coin);
function decrement (i : Integer) return Integer;
procedure decrementList (n : in out Numbers);
end flip_coin;
這是正文文件:
package body flip_coin with SPARK_Mode is
function flip (x : Coin) return Coin
is
begin
if x = Heads then return Tails; else return Heads; end if;
end flip;
procedure flipCoin (x : in out Coin)
is
begin
x := flip(x);
end flipCoin;
function decrement (i : Integer) return Integer
is
begin
return i-1;
end decrement;
procedure decrementList (n : in out Numbers) is
a : Index := n'First;
b : Index := n'Last;
begin
for i in a..b loop
n(i) := decrement(n(i));
end loop;
end decrementList;
end flip_coin;
這是主文件:
with flip_coin; use flip_coin;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
newCoin : Coin := Heads;
numbers : Numbers := (0,1,2,3,4,5,6,7,8,9,10);
begin
Put_Line("Element 9, before decrement:");
Put_Line(numbers(9)'Image);
decrementList(numbers);
Put_Line("Element 9, after decrement:");
Put_Line(numbers(9)'Image);
Put_Line("Coin before flip:");
Put_Line(newCoin'Image);
flipCoin(newCoin);
Put_Line("Coin after flip:");
Put_Line(newCoin'Image);
end Main;
這是我嘗試運行時的錯誤:
main.adb:6:14: object "Numbers" cannot be used before end of its declaration
任何幫助再次非常感謝。 TIA
Ada 是不區分大小寫的語言。 因此,數字和數字是相同的。 如何將數字更改為 numbers_array。
這是一個可見性問題,也是初學者應該避免use <package>
的原因。 了解可見性是了解 Ada 的關鍵。 避免 use-package 子句讓您考慮可見性並幫助您理解它。
您有 2 個名為Numbers
的東西,全名為Flip_Coin.Numbers
和Main.Numbers
。 在Main
中,本地名稱Numbers
對Flip_Coin
隱藏了使用可見的Numbers
。 它仍然可以被稱為Flip_Coin.Numbers
。
Ada 中對可見性的最佳介紹是Ada Distilled 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.