首页 文章

if-else在clojure中分支

提问于
浏览
24

我在教自己Clojure .

在非FP语言中,我可以很容易地编写嵌套if,如果我没有专门放置else,那么控制将只流出if块 . 例如:

Thing myfunc()
{
  if(cond1)
  {
    if(cond2)
      return something;
  }
  return somethingelse;
}

但是,在Clojure中,没有返回语句(我知道),所以如果我写:

(defn myfunc []
  (if (cond1)
      (if (cond2) something))
  somethingelse)

那么“某事”就没有“回归”了 . 它似乎只是说,好吧,这里我们有一个值,现在让我们继续执行 . 显而易见的解决方案是结合条件,即:

(if (and (cond1) (cond2))
    something
    somethingelse)

但是对于大的条件,这会变得笨拙/丑陋 . 此外,还需要额外的finagling来向cond1的“else”部分添加一个语句 . 这有什么优雅的解决方案吗?

5 回答

  • 14

    在Clojure中没有明确的return语句,但是你的代码将在"something"上"return"因为你在 if 之后没有任何表达式而在Clojure中没有 result of the last expression is used as the function’s return value .

  • 14

    您还可以使用 (cond) 宏:

    (defn length-checker [a b]
      (cond
       (= 3 (count (str a))) (if (= 3 (count (str b)))
                       (println "both numbers are 3 digits long")
                       (println "first number is 3 digits, but the 2nd not!"))
       :else (println "first- or both of the numbers are not 3 digits")))
    
  • 30

    这是命令式和功能性方法之间的细微差别 . 通过命令,您可以将 return 放置在函数的任何位置,而功能最好的方法是使用清晰明确的执行路径 . 有些人(包括我)在命令式编程中也更喜欢后一种方法,认为它更明显,易于管理,更不容易出错 .

    要使此功能显式:

    Thing myfunc() {
      if(cond1) {
        if(cond2)
          return something;
      }
    
      return somethingelse;
    }
    

    你可以将它重构为:

    Thing myfunc() {
      if(cond1 && cond2) {
          return something;
      } else {
        return somethingelse;
      }
    }
    

    在Clojure中,它的等价物是:

    (defn myfunc []
      (if (and cond1 cond2) 
          something
          somethingelse))
    

    如果您需要“else”,您的Java版本可能会变为:

    Thing myfunc() {
      if(cond1) {
        if(cond2) {
          return something;
        } else {
          return newelse;
        }
      } else {
        return somethingelse;
      }
    }
    

    ......及其Clojure等价物:

    (defn myfunc []
      (if cond1
          (if cond2 something newelse)
          somethingelse))
    
  • 7

    命令式语言的if语句表示 if this then do that else do that ,函数式语言的if表达式表示 if this return that else return this . 这是一种不同的看待同一个想法的方式,它反映了表达问题的一种非常不同的方法 . 在函数式语言_1545229中,即使你没有对该值做任何事情,也应该是一切 .

    当我进行转换时,它帮助了我自己“这个函数应该返回什么结果”,而不是我习惯要问的“这个函数应该做什么”这个问题 .

  • 0
    (if (and (cond1) (cond2))
         something
         somethingelse)
    
    (cond 
        (and (cond1) (cond2)) something
        :else somethingelse)
    

    如果你想比较同样的东西, cond 会这样做;在开关盒中你可以使用 condp .

    我不经常看到那种代码,但这是做到这一点的方法 .

相关问题