我正在尝试写一些类似于If,else if,else语句的东西。然而,在线编译器给我带来了问题。
我通常用jquery编写代码,然后发出它……但这一次我试图用KRL的方式来做,但我遇到了问题。
当我编写类似下面的代码(在Pre和Post块之间)时,我得到编译器错误:
if (someExpression) then {//执行一些代码} else {//执行一些代码}
我知道这是有原因的。但我需要有人给我解释一下。或者告诉我文档。
发布于 2011-02-15 18:16:34
可以在pre块中使用三元运算符进行变量赋值,如http://kynetxappaday.wordpress.com/2010/12/21/day-15-ternary-operators-or-conditional-expressions/所示
您还可以根据操作块是否触发来有条件地引发显式事件,如http://kynetxappaday.wordpress.com/2010/12/15/day-6-conditional-action-blocks-and-else-postludes/所示
发布于 2011-02-15 22:49:19
对于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 {在Kynetx Docs上有更多关于postlude的文档(例如,fired和notfired )。我也喜欢迈克在Kynetx App A Day上写的更广泛的例子。
发布于 2011-04-07 01:14:17
这是Sam发布的一些代码,解释了如何使用defactions来模仿ifthenelse行为。这位天才的所有功劳都归功于萨姆·柯伦。这可能是你能得到的最好的答案。
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;
}
}
}https://stackoverflow.com/questions/5001879
复制相似问题