F#是否有多路if语句?

3
有没有一种方法可以重构这个代码:
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-way-if

3个回答

4
为什么不直接使用 || -
not (bottom b1>topb2 || top b1<bottom b2 || right b1<left b2 || left b1>right b2)

我就是无法理解这个 :) 这样的表达方式是否等同于原始语句,而没有添加任何否定之处? - undefined
1
@John:为了使您的表达式产生与原始代码片段等效的结果,您应该反转所有条件:bottom b1<=top b2 && ... - undefined
@GeneBelitski 对于否定整个表达式 not (bottom ... && .... && ........) ,如何处理? - undefined
1
@Cetin: not 真的不是 :), (not a)&&(not b) 的等价表达式是 not(a||b) - undefined
2
我认为我现在的内容是正确的 - 但这说明了为什么在写作之前我应该多思考。 - undefined

4
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 

4

在补充 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接