简体   繁体   English

如果F#有多路吗?

[英]Does F# have multi-way if?

Is there a way to refactor this: 有没有办法重构这个:

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

in a more readable way than this: 以比这更可读的方式:

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

?

I am thinking of something similar to multi-way if-expressions in from GHC 7.6.1: http://www.haskell.org/ghc/docs/7.6.1/html/users_guide/syntax-extns.html#multi-way-if . 我正在考虑类似于GHC 7.6.1中的多路if表达式: http//www.haskell.org/ghc/docs/7.6.1/html/users_guide/syntax-extns.html#multi-方式 - 如果

Why not just use || 为什么不使用|| - -

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 

Complementing Brian's answer , it's also worth pointing out that elif is just sugar for else if . 作为Brian的答案的补充,值得指出的是, elif只是else if糖。 ie you can reformat your original code so that it isn't all that bad: 即你可以重新格式化原始代码,以便它不是那么糟糕:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM