2017-03-07 21 views

回答

1

簡單的答案,模式匹配就像鑄造。您可以使用它以不同的方式使靜態類型更爲具體:

value x = ... ; 
if (loc l := x) { 
    // here l will have the type `loc` and have the same value that `x` had 
} 

或:

value x = ...; 
bool myFunc(loc l) = ... ; 
myFunc(x); // /* will only be executed if x is indeeed of type `loc` 

,或者您可以使用模式匹配過濾列表:

list[value] l = ...; 
list[loc] ll = [ e | loc e <- l ]; 

或者,開關:

switch(x) { 
    case loc l: ...; 
} 

等:-)

的通用轉換函數也可以寫,但我認爲這是一個代碼味道使用它,它使代碼難於理解:

&T cast(type[&T] t, value x) { 
    if (&T e := x) 
    return e; 
    throw "cast exception <x> can not be matched to <t>"; 
} 

value x = ...; 
loc l = cast(#loc, x); 
相關問題