2011-02-15 48 views
4

我正在嘗試寫一些與If,else if,else語句相媲美的東西。但是,在線編譯器給我帶來了一些問題。KRL:if then else problems

我通常寫我的代碼在jquery中,只是發射它......但我試圖做到這一點KRL的方式,我遇到了問題。

當我寫類似以下(前置和後置塊之間),我得到的編譯器錯誤:

如果(someExpression)則{// 做一些代碼 }其他{// 做一些代碼 }

我知道有一個原因......但我需要有人向我解釋......或者指向我的文檔。

回答

4

說明隨着KRL明確的事件,通常最好有獨立規則來處理您的問題中描述的「if ... then」和「else」情況。這僅僅是因爲它是一種規則語言;你必須從通常的程序化方式改變你對問題的思考方式。

也就是說,Mike提出明確事件的建議通常是解決問題的最佳方法。這裏有一個例子:

ruleset a163x47 { 
    meta { 
    name "If-then-else" 
    description << 
     How to use explicit events to simulate if..then..else behavior in a ruleset. 
    >> 
    author "Steve Nay" 
    logging off 
    } 
    dispatch { } 
    global { } 

    rule when_true { 
    select when web pageview ".*" 

    //Imagine we have an entity variable that tracks 
    // whether the user is logged in or not 
    if (ent:logged_in) then { 
     notify("My app", "You are already logged in"); 
    } 

    notfired { 
     //This is the equivalent of an else block; we're sending 
     // control to another rule. 
     raise explicit event not_logged_in; 
    } 
    } 

    rule when_false { 
    select when explicit not_logged_in 

    notify("My app", "You are not logged in"); 
    } 
} 

在這個簡單的例子,它也將是很容易寫兩個規則是,除了一個同已在if語句not和其他沒有。這實現相同的目的:

if (not ent:logged_in) then { 

有關於片尾曲(firednotfired,例如),在Kynetx Docs更多的文檔。我還喜歡Mike在Kynetx App A Day上寫的更廣泛的例子。

+1

很好的評論!我在想,我可能需要改變我對它的看法和方法。你的解釋是現貨! – frosty 2011-02-15 15:58:07

2

下面是Sam發佈的一些代碼,它解釋瞭如何使用默認來模仿ifthenelse行爲。這個天才的所有功勞都歸Sam Curren所有。這可能是你可以得到的最好答案。

ruleset a8x152 { 
    meta { 
    name "if then else" 
    description << 
     Demonstrates the power of actions to enable 'else' in krl! 
    >> 
    author "Sam Curren" 
    logging off 
    } 

    dispatch { 
    // Deploy via bookmarklet 
    } 

    global { 
    ifthenelse = defaction(cond, t, f){ 
     a = cond => t | f; 
     a(); 
    }; 
    } 

    rule first_rule { 
    select when pageview ".*" setting() 
    pre { 
     testcond = ent:counter % 2 == 1; 
    } 
    ifthenelse(
     testcond, 
     defaction(){notify("test","counter odd!");}, 
     defaction(){notify("test","counter even!");} 
    ); 
    always { 
     ent:counter += 1 from 1; 
    } 
    } 
}