[英]Does F# have multi-way if?
有没有办法重构这个:
let collide (b1 : Box) (b2 : Box) =
if bottom b1 > top b2
then false
else if top b1 < bottom b2
then false
else if right b1 < left b2
then false
else if left b1 > right b2
then false
else true
以比这更可读的方式:
let collide (b1 : Box) (b2 : Box) =
match () with
| _ when bottom b1 > top b2 -> false
| _ when top b1 < bottom b2 -> false
| _ when right b1 < left b2 -> false
| _ when left b1 > right b2 -> false
| _ -> true
?
我正在考虑类似于GHC 7.6.1中的多路if表达式: http : //www.haskell.org/ghc/docs/7.6.1/html/users_guide/syntax-extns.html#multi-方式 - 如果 。
为什么不使用||
-
not (bottom b1>topb2 || top b1<bottom b2 || right b1<left b2 || left b1>right b2)
let collide (b1 : Box) (b2 : Box) =
if bottom b1 > top b2 then false
elif top b1 < bottom b2 then false
elif right b1 < left b2 then false
elif left b1 > right b2 then false
else true
作为Brian的答案的补充,值得指出的是, elif
只是else if
糖。 即你可以重新格式化原始代码,以便它不是那么糟糕:
let collide (b1 : Box) (b2 : Box) =
if bottom b1 > top b2 then false
else if top b1 < bottom b2 then false
else if right b1 < left b2 then false
else if left b1 > right b2 then false
else true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.