2013-10-30 41 views
2

我發現有時我必須爲模式變量明確指定類型,否則Rascal將無法按預期工作。控制檯中的以下會話說明了這一切:模式變量的類型

rascal>data foo = bar(int); 
ok 

rascal>int x = 1; 
int: 1 

rascal>[x | bar(x) <- [bar(2), bar(3)]]; 
list[void]: [] 

rascal>[x | bar(int x) <- [bar(2), bar(3)]]; 
list[int]: [2,3] 

爲什麼會發生這種情況?

回答

3

在當前版本的Rascal中,周圍範圍中存在的模式中的變量不匹配和映射,而是檢查是否相等。

所以:

<int x, x> := <2,2> => true // x is first introduced and then checked for equality 
<int x, x> := <2,3> => false // x is first introduced and then checked for equality 

{ int x = 1; if (x := 2) println("true"); else println("false"); // false! 

而這對於我們使用模式匹配的所有地方。

我們對這種特殊設計的「非線性匹配」有幾個抱怨,我們打算很快添加一個運算符($)來確定從環繞聲範圍中取出某個東西的意圖。如果不使用運營商,那麼陰影將出現:

<int x, $x> := <2,2> => true // x is first introduced and then checked for equality 
<int x, $x> := <2,3> => false // x is first introduced and then checked for equality 
<int x, x> := <2,3> // static error due to illegal shadowing 
<int x, y> := <2,3> => true // x and y are both introduced 

{ int x = 1; if ($x := 2) println("true"); else println("false"); // false! 
{ int x = 1; if (x := 2) println("true <x>"); else println("false"); // true, prints 2! or perhaps a static error. 

還可以添加一些額外的動力來獲得表達式分成模式爲:

<1, ${1 + 2 + 3}> := <1,6> // true 
+0

啊,謝謝。期待有更多美元的來源,;) – day

+0

:-)你知道我們爲什麼用美元作爲時間日期文字嗎? – jurgenv

+0

呃,沒有。我很好奇,:) – day