[英]How do I create an array in Forth?
我知道,這個問題過去經常被問到,也許這些信息是在以前的 Stack Overflow 帖子中給出的。 但是學習 Forth 是一項非常復雜的任務,重復有助於理解串聯編程語言相對於 C 等替代語言的優勢。
我從 Forth 教程中了解到,Forth 不提供創建二維數組的命令,但用戶必須在程序中從頭開始實現所有內容。 我在 Forth 中找到了兩種占用內存的選項。 首先通過創建一個新詞:
: namelist s” hello” s” world” ;
或者其次通過 CREATE 語句:
create temperature 10 allot
temperature 10 cells dump
到現在為止還挺好; 我們創建了一個包含 10 個單元格的數組,其中可以存儲整數變量。 但是,如果我需要保存浮點數呢? 我必須始終將 float 轉換為 int 還是可以將它們保存到普通單元格中?
另一個未解決的問題是如何在數組中存儲字符串值。 據我所知,一個字符串包含一個指針加上一個大小。 所以理論上我只能在 10 個單元格數組中存儲 5 個字符串,另外我需要在其他地方保存字符串本身的內存。 那沒有多大意義。
是否有某種更高的抽象可用於將值存儲在可用於編寫易於閱讀的程序的數組中? 我的意思是,如果每個程序員都使用自己的 Forth 方法在內存中存儲一些東西,其他程序員會發現很難閱讀代碼。
create
創建一個返回字典(數據空間)中緩沖區地址的單詞; 它最初為零長度,因此您必須立即為其保留所需的空間。
allot
以地址單位(通常是字節)衡量的保留空間,因此您必須以字節為單位計算所需的大小。
例如:
create a 10 cells allot
create b 10 floats allot
它只是緩沖區,您仍然需要處理指針算術來獲取或設置項目,例如:
: create-floats-array ( length "name" -- ) create floats allot does> swap 1- floats + ;
10 create-floats-array c
0.35e 3 c f! \ store the float number into third item (1-based indexing)
3 c f@ f. \ print float number form third item
在字典中創建浮點數組的單詞示例:
: create-floats-array ( length "name" -- ) create floats allot does> swap 1- floats + ; 10 create-floats-array c 0.35e 3 cf! \\ store the float number into third item (1-based indexing) 3 cf@ f. \\ print float number form third item
如果您需要許多數組和許多字符串,最好使用適當的庫。 例如,請參閱Forth Foundation Library 中的元胞數組模塊和動態文本字符串模塊。
元素的廣義 2darray。 將元素大小作為參數
\ size is the per element multiplier
\ n size * is the per_row factor
\ m n size * * is the total space required
: 2darray \ create> m n size -- ; does> mix nix -- a
\ size is the number of bytes for one element
\
create 2dup * , \ multiplier to apply to m index
dup , \ multiplier to apply to n index
* * allot \ calculate total bytes and allot them
does> \ mix nix -- a
>r r@ cell+ @ * \ offset from n index
swap r@ @ * + \ offset with m index
r> + 2 cells+ \ 2 cells offset for the 'admin' cells
;
例子
50 40 /float 2darray 50x40floats
50 40 2 cells 2darray 50x40stringpairs
甚至
20 constant /record
10 200 /record 2darray 2000records
你對字符串感到困惑。 該字符串只是進入內存,並為該字符串分配該地址的內存,並且它永遠存在(除非您更改它)。
因此,如果您想在分配的內存塊中存儲 5 個(c-addr u)字符串(稱其為數組有點牽強),您可以將 c-addr 存儲在單元格n 中,將長度 u 存儲在單元格中n+1 。
如果您擔心 10 個單元格的空間很大(這真的沒什么可擔心的)並且只想使用 5 個單元格,您可以將字符串存儲為計數字符串,使用像C"
這樣的單詞 - 計數字符串將長度存儲在第一個字節,隨后的每個字節都是一個字符。
此外,您可以使用單詞,
(逗號)將內容存儲到當前dp
的字典中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.