简体   繁体   中英

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 .

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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