2013-08-19 32 views
2

我試圖找出這個Java的Clojure中的等價物:如果斷Clojure中

public int compute(int x) { 
    if (x < 0) return 0;  

    // continue do some computing 
    return result; 
} 

是否有地道的Clojure是「破發」的處理函數中,並返回結果?

+0

(if)form? (如果測試(when-true)(when-false)) – Chiron

+0

我建議通過教程或查看代碼示例來了解Clojure中的控制流。那麼,如果仍然不清楚,你可以提出一個更好的問題。 –

回答

3

沒有短路return聲明(或breakgoto ...)。返回是隱含的。

幾乎等效Clojure中你的例子是

(defn test [x] 
    (if (< x 0) 
     0 
     (let [result (comment compute result)] 
      result))) 

但你可能會回到result沒有將其命名爲:

(defn test [x] 
    (if (< x 0) 
     0 
     (comment compute result))) 

這些運行,但comment始終計算爲nil

順便說一句,如果測試失敗,帶有兩個表達式(而不是全三)的if結構將返回nil

(if (< 3 0) 0) ; nil 

所以總會有東西要回來。

2

Clojure沒有像這樣的return語句,但只要在if語句中有一個非常簡單的代碼分支就可以達到類似的結果。

(defn compute [x] 
    (if (< x 0) 0 
     (do ... 
      result))) 

你也可以做cond或也許單子類似的東西。

+1

'0'不是一個空分支,它只是一個非常簡單的 – noisesmith

+0

@noisesmith true,已更新。 – obmarg

5

使用Clojure進行編程時,一個主要的指導原則是,一切都「返回」了一個值,儘管它通常被表述爲「一切都以某種方式評估」。在調用函數時,函數的結果是函數中最後一個表達式的結果。

user> (defn foo [] 1 2 3 4) 
#'user/foo 
user> (foo) 
4 

有表達 「提前終止」 的理念幾種形式:

user> (defn compute [x] (cond (< x 0) 0 :default (* x 42))) 
#'user/compute 
user> (compute 1) 
42 

user> (defn compute [x] (if-let [y (< x 0)] (* 8 y) (* 4 x))) 
#'user/compute 
user> (compute 1) 
4 

或簡單if表達。一個重要的概念就是一切都會帶來新的價值。這催生了Clojure的社會上很多buzwords包括「價值導向編程」

2

你真的需要指定:

// continue do some computing 

一個例子..

public int test(int x) { 
    if (x < 0) 
     return 0;  

    int tmp = getSomthing1(x); 
    int tmp2 = getSomething2(x, tmp); 
    int result = tmp/tmp2; 
    return result; 
} 

這將是財產以後這樣的:

(defn test [x] 
    (if (< x 0) 
     0 
     (let [tmp (getSomthing1 x) 
       tmp2 (getSomething2 x tmp)] 
      (/ tmp tmp2)))) 

你有什麼是(if predicate consequent alternative)let可以保持中間計算而不必轉動代碼。