跳轉到內容

Clojure 學習/歷史

來自華夏公益教科書,開放的世界,開放的書籍
Clojure 學習 Next page
安裝
歷史

Lisp 是所有程式語言中最古老的一種,由約翰·麥卡錫於 1958 年發明。最初的語言衍生出許多變體方言,今天最流行的是 Common LispSchemeClojure (發音為 "closure") 是由 Rich Hickey 建立的一種新的 Lisp 方言。與 Scheme 一樣,Clojure 是一種 函式式 方言,這意味著它支援和鼓勵以 "函式式風格" 進行程式設計。

然而,Clojure 在幾個重要方面與舊的 lisp 不同。Clojure 程式碼有更多的語法糖。例如,與其輸入 (set 1 2 3),不如寫 #{1 2 3}。Clojure 從 Python 和 Haskell 中借鑑了它對啞資料結構的依賴:集合、對映、列表和向量。其中大多數都有自己的語法糖。Clojure 大量使用向量資料結構(類似於 Java 陣列,在 Clojure 中用 `[]' 表示),在可能的情況下優先於列表,原因是美觀和效能。Clojure 還具有與 Java 庫的完全互操作性。

為了讓你感受一下這種語言,這裡有一個用 Clojure 編寫的簡單示例程式,用於糾正拼寫(這是 Peter Norvig 的 Python 拼寫糾正器的 Clojure 翻譯)

 (defn words [text] (re-seq #"[a-z]+" (.toLowerCase text)))
 
 (defn train [features]
   (reduce (fn [model f] (assoc model f (inc (get model f 1)))) {} features))
 
 (def *nwords* (train (words (slurp "big.txt"))))
 
 (defn edits1 [word]
   (let [alphabet "abcdefghijklmnopqrstuvwxyz", n (count word)]
     (distinct (concat
       (for [i (range n)] (str (subs word 0 i) (subs word (inc i))))
       (for [i (range (dec n))]
         (str (subs word 0 i) (nth word (inc i)) (nth word i) (subs word (+ 2 i))))
       (for [i (range n) c alphabet] (str (subs word 0 i) c (subs word (inc i))))
       (for [i (range (inc n)) c alphabet] (str (subs word 0 i) c (subs word i)))))))
 
 (defn known [words nwords] (seq (for [w words :when (nwords w)]  w)))
 
 (defn known-edits2 [word nwords] (seq (for [e1 (edits1 word) e2 (edits1 e1) :when (nwords e2)]  e2)))
 
 (defn correct [word nwords]
   (let [candidates (or (known [word] nwords) (known (edits1 word) nwords) 
                        (known-edits2 word nwords) [word])]
     (apply max-key #(get nwords % 1) candidates)))

在本檔案結束時,你應該能夠理解這段程式碼(在 API 參考的幫助下)。

華夏公益教科書