跳轉到內容

Raku 程式設計/連線

來自華夏公益教科書,開放的書籍,為開放的世界

連線最初是作為 Perl 模組的一部分實現的,目的是簡化一些常見操作。假設有一個複雜的條件,需要將變數 $x 與多個離散值進行比較

if ($x == 2 || $x == 4 || $x == 5 || $x == "hello" 
 || $x == 42 || $x == 3.14)

這是一個很大的混亂。我們想要做的是建立一個值列表,並詢問“如果 $x 是這些值中的一個”。連線允許這種行為,但可以做更多的事情。以下是相同的語句,寫成連線

if ($x == (2|4|5|"hello"|42|3.14))

連線型別

[編輯 | 編輯原始碼]

有 4 種基本型別的連線:any(所有元件的邏輯 OR),all(所有元件的邏輯 AND),one(所有元件的邏輯 XOR),以及 none(所有元件的邏輯 NOR)。

列表運算子

[編輯 | 編輯原始碼]

列表運算子將連線構建為列表

my $options = any(1, 2, 3, 4);        # Any of these is good
my $requirements = all(5, 6, 7, 8);   # All or nothing
my $forbidden = none(9, 10, 11);      # None of these
my $onlyone = one(12, 13, 4);         # One and only one

中綴運算子

[編輯 | 編輯原始碼]

指定連線的另一種方法是使用我們已經見過的中綴運算子

my $options = 1 | 2 | 3 | 4;        # Any of these is good
my $requirements = 5 & 6 & 7 & 8;   # All or nothing
my $onlyone = 12 ^ 13 ^ 4;          # One and only one

請注意,沒有中綴運算子來建立 none() 連線。

連線操作

[編輯 | 編輯原始碼]

匹配連線

[編輯 | 編輯原始碼]

連線與 Raku 中的任何其他資料型別一樣,可以使用 智慧匹配 運算子 ~~ 進行匹配。運算子會根據正在匹配的連線型別自動執行正確的匹配演算法。

my $junction = any(1, 2, 3, 4);
if $x ~~ $junction {
    # execute block if $x is 1, 2, 3, or 4
}

all() 連線

[編輯 | 編輯原始碼]
if 1 ~~ all(1, "1", 1.0)     # Success, all of them are equivalent
if 2 ~~ all(2.0, "2", "foo") # Failure, the last one doesn't match

只有當 all() 連線中的所有元素都與物件 $x 匹配時,才會匹配。如果任何元素不匹配,則整個匹配失敗。

one() 連線

[編輯 | 編輯原始碼]

one() 連線只有當且僅當其中一個元素匹配時才會匹配。多於或少於一個,整個匹配都會失敗。

if 1 ~~ one(1.0, 5.7, "garbanzo!") # Success, only one match
if 1 ~~ one(1.0, 5.7, Int)         # Failure, two elements match

any() 連線

[編輯 | 編輯原始碼]

只要 至少一個 元素匹配,any() 連線就會匹配。它可以是一個或多個,但不能為零。any 連線失敗的唯一情況是所有元素都不匹配。

if "foo" ~~ any(String, 5, 2.18)  # Success, "foo" is a String
if "foo" ~~ any(2, Number, "bar") # Failure, none of these match

none() 連線

[編輯 | 編輯原始碼]

none() 連線只有當連線中的所有元素都不匹配時才成功。這樣,它等同於 any() 連線的逆。如果 any() 成功,則 none() 失敗。如果 any() 失敗,則 none() 成功。

if $x ~~ none(1, "foo", 2.18)
if $x !~ any(1, "foo", 2.18)    # Same thing!
華夏公益教科書