震惊小伙伴的单行代码●Clojure篇

几年前,函数式编程的复兴正值巅峰,一篇介绍 Scala 中 10 个单行函数式代码的博文在网上走红。很快地,一系列使用其他语言实现这些单行代码的文章也随之出现,比如 Haskell, Ruby, Groovy, Clojure, Python, C#, F#, CoffeeScript

每篇文章都令人印象深刻的揭示了这些语言中一些出色优秀的编程特征。编程高手们利用这些技巧提高编程速度、改进软件质量,编程初学者能从这些简洁的预防中学到各种编程语言的真谛。本《震惊小伙伴的单行代码系列》将逐一介绍这些各种编程语言单行代码文章,供大家学习参考。

1、让列表中的每个元素都乘以2

(map #(* % 2) (range 1 11))

2、求列表中的所有元素之和

(reduce + (range 1 1001))

3、判断一个字符串中是否存在某些词

我这里使用了正则表达式,因为我觉得这是最优方法。

(def tweet "This is an example tweet talking about clojure and emacs.")
(def is-word? (set ["clojure" "logic" "compojure" "emacs" "macros"]))
(not (nil? (some is-word? (.split tweet " ")))) ; Returns true/false

4、读取文件

(def file-text (slurp "data.txt")) ; Reads the whole file
(def file-lines (clojure.contrib.io/read-lines "data.txt")) ; Reads as a sequence of lines

Since Clojure Contrib has been deprecated for future Clojure releases, clojure.contrib.io/read-lines can be rewritten as (line-seq (clojure.java.io/reader (clojure.java.io/file “data.txt”))) in Clojure 1.3 onwards. Thanks to Aaron for pointing it out.

5、祝你生日快乐!

(doseq [l (map #(str "Happy Birthday " (if (= % 2) "dear Rich" "to You")) (range 4))] (println l))

或者

(dotimes [n 4] (println "Happy Birthday " (if (= n 2) "dear Rich" "to You")))

6. 过滤列表中的数值

(partition-by #(> % 60) [49 58 76 82 88 90])

7. 获取XML web service数据并分析

(clojure.xml/parse "http://search.twitter.com/search.atom?&q=clojure")

8. 找到列表中最小或最大的一个数字

(reduce max [14 35 -7 46 98])
(reduce min [14 35 -7 46 98])
;; Now both together
((juxt #(reduce max %) #(reduce min %)) [14 35 -7 46 98]) ; Returns [98 -7]

9. 并行处理

;; Assuming process-line to be a CPU intensive function that operates on a line
(pmap process-line lines) ; Note the "p" in front of map

10. “Sieve of Eratosthenes”算法

I don’t I have a sufficiently good (in terms of performance & beauty) one line implementation of SoE. I would recommend checking out Christophe Grand’s treatise on the subject titled Everybody loves the Sieve of Eratosthenes for a great discussion on writing real world prime sieves in Clojure.

分享这篇文章:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

壹加壹等于