加载中...

clojure


其中 Y=clojure

源代码下载: learnclojure-cn.clj

Clojure是运行在JVM上的Lisp家族中的一员。她比Common Lisp更强调纯函数式编程,且自发布时便包含了一组工具来处理状态。

这种组合让她能十分简单且自动地处理并发问题。

(你需要使用Clojure 1.2或更新的发行版)

  1. ; 注释以分号开始。
  2. ; Clojure代码由一个个form组成, 即写在小括号里的由空格分开的一组语句。
  3. ; Clojure解释器会把第一个元素当做一个函数或者宏来调用,其余的被认为是参数。
  4. ; Clojure代码的第一条语句一般是用ns来指定当前的命名空间。
  5. (ns learnclojure)
  6. ; 更基本的例子:
  7. ; str会使用所有参数来创建一个字符串
  8. (str "Hello" " " "World") ; => "Hello World"
  9. ; 数学计算比较直观
  10. (+ 1 1) ; => 2
  11. (- 2 1) ; => 1
  12. (* 1 2) ; => 2
  13. (/ 2 1) ; => 2
  14. ; 等号是 =
  15. (= 1 1) ; => true
  16. (= 2 1) ; => false
  17. ; 逻辑非
  18. (not true) ; => false
  19. ; 嵌套的form工作起来应该和你预想的一样
  20. (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2
  21. ; 类型
  22. ;;;;;;;;;;;;;
  23. ; Clojure使用JavaObject来描述布尔值、字符串和数字
  24. ; 用函数 `class` 来查看具体的类型
  25. (class 1) ; 整形默认是java.lang.Long类型
  26. (class 1.); 浮点默认是java.lang.Double类型的
  27. (class ""); Stringjava.lang.String类型的,要用双引号引起来
  28. (class false) ; 布尔值是java.lang.Boolean类型的
  29. (class nil); "null"被称作nil
  30. ; 如果你想创建一组数据字面量,用单引号(')来阻止form被解析和求值
  31. '(+ 1 2) ; => (+ 1 2)
  32. ; (单引号是quote的简写形式,故上式等价于(quote (+ 1 2)))
  33. ; 可以对一个引用列表求值
  34. (eval '(+ 1 2)) ; => 3
  35. ; 集合(Collection)和序列
  36. ;;;;;;;;;;;;;;;;;;;
  37. ; List的底层实现是链表,Vector的底层实现是数组
  38. ; 二者也都是java类
  39. (class [1 2 3]); => clojure.lang.PersistentVector
  40. (class '(1 2 3)); => clojure.lang.PersistentList
  41. ; list本可以写成(1 2 3), 但必须用引用来避免被解释器当做函数来求值。
  42. ; (list 1 2 3)等价于'(1 2 3)
  43. ; 集合其实就是一组数据
  44. ; List和Vector都是集合:
  45. (coll? '(1 2 3)) ; => true
  46. (coll? [1 2 3]) ; => true
  47. ; 序列 (seqs) 是数据列表的抽象描述
  48. ; 只有列表才可称作序列。
  49. (seq? '(1 2 3)) ; => true
  50. (seq? [1 2 3]) ; => false
  51. ; 序列被访问时只需要提供一个值,所以序列可以被懒加载——也就意味着可以定义一个无限序列:
  52. (range 4) ; => (0 1 2 3)
  53. (range) ; => (0 1 2 3 4 ...) (无限序列)
  54. (take 4 (range)) ; (0 1 2 3)
  55. ; cons用以向列表或向量的起始位置添加元素
  56. (cons 4 [1 2 3]) ; => (4 1 2 3)
  57. (cons 4 '(1 2 3)) ; => (4 1 2 3)
  58. ; conj将以最高效的方式向集合中添加元素。
  59. ; 对于列表,数据会在起始位置插入,而对于向量,则在末尾位置插入。
  60. (conj [1 2 3] 4) ; => [1 2 3 4]
  61. (conj '(1 2 3) 4) ; => (4 1 2 3)
  62. ; 用concat来合并列表或向量
  63. (concat [1 2] '(3 4)) ; => (1 2 3 4)
  64. ; filter来过滤集合中的元素,用map来根据指定的函数来映射得到一个新的集合
  65. (map inc [1 2 3]) ; => (2 3 4)
  66. (filter even? [1 2 3]) ; => (2)
  67. ; recuce使用函数来规约集合
  68. (reduce + [1 2 3 4])
  69. ; = (+ (+ (+ 1 2) 3) 4)
  70. ; => 10
  71. ; reduce还能指定一个初始参数
  72. (reduce conj [] '(3 2 1))
  73. ; = (conj (conj (conj [] 3) 2) 1)
  74. ; => [3 2 1]
  75. ; 函数
  76. ;;;;;;;;;;;;;;;;;;;;;
  77. ; 用fn来创建函数。函数的返回值是最后一个表达式的值
  78. (fn [] "Hello World") ; => fn
  79. ; (你需要再嵌套一组小括号来调用它)
  80. ((fn [] "Hello World")) ; => "Hello World"
  81. ; 你可以用def来创建一个变量(var)
  82. (def x 1)
  83. x ; => 1
  84. ; 将函数定义为一个变量(var)
  85. (def hello-world (fn [] "Hello World"))
  86. (hello-world) ; => "Hello World"
  87. ; 你可用defn来简化函数的定义
  88. (defn hello-world [] "Hello World")
  89. ; 中括号内的内容是函数的参数。
  90. (defn hello [name]
  91. (str "Hello " name))
  92. (hello "Steve") ; => "Hello Steve"
  93. ; 你还可以用这种简写的方式来创建函数:
  94. (def hello2 #(str "Hello " %1))
  95. (hello2 "Fanny") ; => "Hello Fanny"
  96. ; 函数也可以有多个参数列表。
  97. (defn hello3
  98. ([] "Hello World")
  99. ([name] (str "Hello " name)))
  100. (hello3 "Jake") ; => "Hello Jake"
  101. (hello3) ; => "Hello World"
  102. ; 可以定义变参函数,即把&后面的参数全部放入一个序列
  103. (defn count-args [& args]
  104. (str "You passed " (count args) " args: " args))
  105. (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"
  106. ; 可以混用定参和变参(用&来界定)
  107. (defn hello-count [name & args]
  108. (str "Hello " name ", you passed " (count args) " extra args"))
  109. (hello-count "Finn" 1 2 3)
  110. ; => "Hello Finn, you passed 3 extra args"
  111. ; 哈希表
  112. ;;;;;;;;;;
  113. ; 基于hash的map和基于数组的map(即arraymap)实现了相同的接口,hashmap查询起来比较快,
  114. ; 但不保证元素的顺序。
  115. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap
  116. (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap
  117. ; arraymap在足够大的时候,大多数操作会将其自动转换成hashmap,
  118. ; 所以不用担心(对大的arraymap的查询性能)。
  119. ; map支持很多类型的key,但推荐使用keyword类型
  120. ; keyword类型和字符串类似,但做了一些优化。
  121. (class :a) ; => clojure.lang.Keyword
  122. (def stringmap {"a" 1, "b" 2, "c" 3})
  123. stringmap ; => {"a" 1, "b" 2, "c" 3}
  124. (def keymap {:a 1, :b 2, :c 3})
  125. keymap ; => {:a 1, :c 3, :b 2}
  126. ; 顺便说一下,map里的逗号是可有可无的,作用只是提高map的可读性。
  127. ; 从map中查找元素就像把map名作为函数调用一样。
  128. (stringmap "a") ; => 1
  129. (keymap :a) ; => 1
  130. ; 可以把keyword写在前面来从map中查找元素。
  131. (:b keymap) ; => 2
  132. ; 但不要试图用字符串类型的key来这么做。
  133. ;("a" stringmap)
  134. ; => Exception: java.lang.String cannot be cast to clojure.lang.IFn
  135. ; 查找不存在的key会返回nil。
  136. (stringmap "d") ; => nil
  137. ; 用assoc函数来向hashmap里添加元素
  138. (def newkeymap (assoc keymap :d 4))
  139. newkeymap ; => {:a 1, :b 2, :c 3, :d 4}
  140. ; 但是要记住的是clojure的数据类型是不可变的!
  141. keymap ; => {:a 1, :b 2, :c 3}
  142. ; 用dissoc来移除元素
  143. (dissoc keymap :a :b) ; => {:c 3}
  144. ; 集合(Set)
  145. ;;;;;;
  146. (class #{1 2 3}) ; => clojure.lang.PersistentHashSet
  147. (set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3}
  148. ; 用conj新增元素
  149. (conj #{1 2 3} 4) ; => #{1 2 3 4}
  150. ; 用disj移除元素
  151. (disj #{1 2 3} 1) ; => #{2 3}
  152. ; 把集合当做函数调用来检查元素是否存在:
  153. (#{1 2 3} 1) ; => 1
  154. (#{1 2 3} 4) ; => nil
  155. ; 在clojure.sets模块下有很多相关函数。
  156. ; 常用的form
  157. ;;;;;;;;;;;;;;;;;
  158. ; clojure里的逻辑控制结构都是用宏(macro)实现的,这在语法上看起来没什么不同。
  159. (if false "a" "b") ; => "b"
  160. (if false "a") ; => nil
  161. ; 用let来创建临时的绑定变量。
  162. (let [a 1 b 2]
  163. (> a b)) ; => false
  164. ; 用do将多个语句组合在一起依次执行
  165. (do
  166. (print "Hello")
  167. "World") ; => "World" (prints "Hello")
  168. ; 函数定义里有一个隐式的do
  169. (defn print-and-say-hello [name]
  170. (print "Saying hello to " name)
  171. (str "Hello " name))
  172. (print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff")
  173. ; let也是如此
  174. (let [name "Urkel"]
  175. (print "Saying hello to " name)
  176. (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
  177. ; 模块
  178. ;;;;;;;;;;;;;;;
  179. ; 用use来导入模块里的所有函数
  180. (use 'clojure.set)
  181. ; 然后就可以使用set相关的函数了
  182. (intersection #{1 2 3} #{2 3 4}) ; => #{2 3}
  183. (difference #{1 2 3} #{2 3 4}) ; => #{1}
  184. ; 你也可以从一个模块里导入一部分函数。
  185. (use '[clojure.set :only [intersection]])
  186. ; 用require来导入一个模块
  187. (require 'clojure.string)
  188. ; 用/来调用模块里的函数
  189. ; 下面是从模块`clojure.string`里调用`blank?`函数。
  190. (clojure.string/blank? "") ; => true
  191. ; `import`里你可以给模块名指定一个较短的别名。
  192. (require '[clojure.string :as str])
  193. (str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst."
  194. ; (#""用来表示一个正则表达式)
  195. ; 你可以在一个namespace定义里用:require的方式来require(或use,但最好不要用)模块。
  196. ; 这样的话你无需引用模块列表。
  197. (ns test
  198. (:require
  199. [clojure.string :as str]
  200. [clojure.set :as set]))
  201. ; Java
  202. ;;;;;;;;;;;;;;;;;
  203. ; Java有大量的优秀的库,你肯定想学会如何用clojure来使用这些Java库。
  204. ; 用import来导入java类
  205. (import java.util.Date)
  206. ; 也可以在ns定义里导入
  207. (ns test
  208. (:import java.util.Date
  209. java.util.Calendar))
  210. ; 用类名末尾加`.`的方式来new一个Java对象
  211. (Date.) ; <a date object>
  212. ; 用`.`操作符来调用方法,或者用`.method`的简化方式。
  213. (. (Date.) getTime) ; <a timestamp>
  214. (.getTime (Date.)) ; 和上例一样。
  215. ; 用`/`调用静态方法
  216. (System/currentTimeMillis) ; <a timestamp> (system is always present)
  217. ; 用`doto`来更方便的使用(可变)类。
  218. (import java.util.Calendar)
  219. (doto (Calendar/getInstance)
  220. (.set 2000 1 1 0 0 0)
  221. .getTime) ; => A Date. set to 2000-01-01 00:00:00
  222. ; STM
  223. ;;;;;;;;;;;;;;;;;
  224. ; 软件内存事务(Software Transactional Memory)被clojure用来处理持久化的状态。
  225. ; clojure里内置了一些结构来使用STM。
  226. ; atom是最简单的。给它传一个初始值
  227. (def my-atom (atom {}))
  228. ; 用`swap!`更新atom。
  229. ; `swap!`会以atom的当前值为第一个参数来调用一个指定的函数,
  230. ; `swap`其余的参数作为该函数的第二个参数。
  231. (swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1)
  232. (swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2)
  233. ; 用`@`读取atom的值
  234. my-atom ;=> Atom<#...> (返回Atom对象)
  235. @my-atom ; => {:a 1 :b 2}
  236. ; 下例是一个使用atom实现的简单计数器
  237. (def counter (atom 0))
  238. (defn inc-counter []
  239. (swap! counter inc))
  240. (inc-counter)
  241. (inc-counter)
  242. (inc-counter)
  243. (inc-counter)
  244. (inc-counter)
  245. @counter ; => 5
  246. ; 其他STM相关的结构是ref和agent.
  247. ; Refs: http://clojure.org/refs
  248. ; Agents: http://clojure.org/agents

进阶读物

本文肯定不足以讲述关于clojure的一切,但是希望足以让你迈出第一步。

Clojure.org官网有很多文章: http://clojure.org/

Clojuredocs.org有大多数核心函数的文档,还带了示例哦:http://clojuredocs.org/quickref/Clojure%20Core

4Clojure是个很赞的用来练习clojure/FP技能的地方: http://www.4clojure.com/

Clojure-doc.org (你没看错)有很多入门级的文章: http://clojure-doc.org/


还没有评论.