Clojure Java平台的Erlang

初次接触clojure是在08年的4月份,接触的理由很简单,clojure基于jvm。本人文笔不好,转一篇来描述一下clojure

转载:http://www.iteye.com/news/117

Erlang是近两年非常吸引眼球的函数式编程语言,因为Erlang能够做到code-as-data,以及数据不变的特性,因此非常适合大规模,高并发负载的应用环境。特别是随着现在多核CPU的广泛应用,并行运算成为了一个热点话题。


作为当今最主流的运算平台JVM,把函数式编程语言引入JVM也是很多人尝试的方向,Clojure就是其中之一。Clojure是一个在JVM平台运行的动态函数式编程语言,其语法解决于LISP语言,在JVM平台运行的时候,会被编译为JVM的字节码进行运算。 

Clojure保持了函数式语言的主要特点,例如immutable state,Full Lisp-style macro support,persistent data structures等等,并且还能够非常方便的调用Java类库的API,和Java类库进行良好的整合。 

Java整合示例: 

Java代码 复制代码
  1. (new java.util.Date)   
  2. => Wed Oct 17 20:01:38 CEST 2007  
  3.   
  4. (. (new java.util.Date) (getTime))   
  5. => 1192644138751    
  6.   
  7. (.. System out (println "This is cool!"))   
  8. This is cool!  
  1. (new java.util.Date)  
  2. => Wed Oct 17 20:01:38 CEST 2007  
  3.   
  4. (. (new java.util.Date) (getTime))  
  5. => 1192644138751   
  6.   
  7. (.. System out (println "This is cool!"))  
  8. This is cool!  



Lisp风格的宏 

Java代码 复制代码
  1. (defmacro time [form]   
  2.   `(let [t0# (. System (currentTimeMillis))   
  3.          res# ~form   
  4.          t1# (. System (currentTimeMillis))]   
  5.     (.. System out (println (strcat "Execution took "  
  6.                                     (/ (- t1# t0#) 1000.0" s")))   
  7.     res#))   
  8.   
  9. Usage:   
  10. (defn factorial [n]   
  11.    (if (< n 2)   
  12.        1  
  13.        (* n (factorial (- n 1)))))   
  14.   
  15. (time (factorial 1000))   
  16. => Execution took 0.012 s   
  17.      40…  
  1. (defmacro time [form]  
  2.   `(let [t0# (. System (currentTimeMillis))  
  3.          res# ~form  
  4.          t1# (. System (currentTimeMillis))]  
  5.     (.. System out (println (strcat "Execution took "  
  6.                                     (/ (- t1# t0#) 1000.0" s")))  
  7.     res#))  
  8.   
  9. Usage:  
  10. (defn factorial [n]  
  11.    (if (< n 2)  
  12.        1  
  13.        (* n (factorial (- n 1)))))  
  14.   
  15. (time (factorial 1000))  
  16. => Execution took 0.012 s  
  17.      40…  



也许,Clojure将成为JVM平台的Erlang,想想看,Clojure还能够直接调用Java的类库,真是令人兴奋。 

Clojure的主页: 

http://clojure.sourceforge.net/

原文地址:https://www.cnblogs.com/bozhang/p/3114910.html