在函数型语言中,所有的语句都有返回值,当然 if..else 也不例外。这个功能在命令型语言中是没有的。
比如以下代码:
public function foo(a:int):int {
if(a<0) {
return -1
}else if(a==0) {
return 0
}else{
return 1
}
}
既难读也麻烦。如果使用 haskell(一种函数型语言) 来写的话:
foo a = if a<0 then -1
else if a==0 then 0
else 1
十分简练。注意,AS3.0 有一个 :? 运算符,可以用它来实现,如果把格式写好的话,可读性会比 if..else 还要好。
public function foo(a:int):int {
return a<0 ? -1 :
a==0 ? 0 :
1;
}
当 if..else 相套时,可以这样写:
public function foo2(x:int, y:int):int {
return x>0 ? (
y>0 ? 1 :
y<0 ? 4 :
-1
):
x<0 ? (
y>0 ? 2 :
y<0 ? 3 :
-1
):
-1;
}
![[Google]](http://www.google.com/logos/Logo_25wht.gif)
![[Synchronous Space]](http://weihe924stephen.googlepages.com/syncspace-banner.jpg)
![[Creative Commons License]](http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png)
![[Add to Google]](http://buttons.googlesyndication.com/fusion/add.gif)
![[Aggregated by MXNA]](http://weblogs.macromedia.com/mxna/images/mxna88x31.gif)
![[Flex.org]](http://www.flex.org/images/flexorg.gif)
![Validate my Atom 1.0 feed [Valid Atom 1.0]](http://validator.w3.org/feed/images/valid-atom.png)
![Validate my RSS feed [Valid RSS]](http://resource.googlecode.com/files/valid-rss.png)
![[I heart FeedBurner]](http://www.feedburner.com/fb/images/pub/i_heart_fb.gif)
没有评论:
发表评论