簡體   English   中英

如果F#有多路嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM