2014-12-30 27 views
-1

我寫了一個簡單的python功能爲我的朋友告訴爲什麼現在一些是素:如何迭代Clojure中的一系列數字?

def why_not_prime(n): 
    if n==2: 
     print(n, "is a prime.") 
    for i in range(2,n): 
     if n%i == 0: 
      print(n, "is not a prime because it could be divided by", i,".") 
      break 
     else: 
      print(n, "is a prime.") 
      break 

我嘗試將其轉換爲Clojure,但我無法找到路。我不知道如何處理for i in range(2,n)。通常的做法是什麼?

+1

我不認爲你花費很多時間檢查甚至介紹Clojure的文章。搜索'clojure'和'looping'立即找到相關文章:https://clojuredocs.org/clojure.core/loop – schaueho

+0

我很確定這個聲明'9'是一個素數。基本上,任何不能被'2'整除的非素數都被稱爲素數。 – resueman

+0

@schaueho感謝您指向我的文檔鏈接。我需要閱讀更多文檔。 – Nick

回答

2

在Clojure中,實際上沒有普遍的答案,因爲它是由決定的,爲什麼你要遍歷這些數字
您可能希望爲每個數字生成一些值,然後將其收集到列表中,在這種情況下,您想要使用mapfor。您可能想要以某種方式「總結」它們(如將它們全部添加在一起),在這種情況下,您想要使用諸如reduce之類的東西。
在這種情況下,您需要一種特殊的摘要;你想知道是否有某個值在「適當」的範圍內(在這種情況下,除數爲n)。這種用例稱爲some有一個核心功能,但它需要一個函數來告訴它什麼是「合適的」值。沒有任何基本功能可以完成所有我們想要的功能,但我們可以創建一個。現在

(defn why-not-prime [n] 
    (let[checker (fn [divisor] ;; A local function under the name checker, with one argument 
       (if (= 0 (mod n divisor));; If that argument is a divisor of n 
        divisor ;;then return it 
        false)) ;; otherwise return false - this value wasn't "appropriate" 
     witness (some checker (range 2 n))] ;; witness will be the first value that satisfies checker 
       ;if there isn't such a value, witness is nil 
    (if witness 
     (str n " is composite because it can be divided by " witness) 
     (str n " is prime.")))) 

,這種略帶重新定義你的問題,因爲它不打印的任何消息,但只有包含一個字符串。這是一種功能性語言中更慣用的表述,通常您會盡可能延遲印刷等副作用。如果你想打印它,你可以用println包裝整個功能體。

+1

非常感謝!你的解決方案'checker - > witness'非常清楚,這個解釋對新手來說很有幫助。在閱讀您的解決方案後,我決定:1.檢查文檔中的「some」功能。 2.閱讀一本Clojure書。 – Nick