Clojure - Java平台的Erlang

26 篇文章 0 订阅

转载: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!  
(new java.util.Date)
=> Wed Oct 17 20:01:38 CEST 2007

(. (new java.util.Date) (getTime))
=> 1192644138751 

(.. System out (println "This is cool!"))
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…  
(defmacro time [form]
  `(let [t0# (. System (currentTimeMillis))
         res# ~form
         t1# (. System (currentTimeMillis))]
    (.. System out (println (strcat "Execution took "
                                    (/ (- t1# t0#) 1000.0) " s")))
    res#))

Usage:
(defn factorial [n]
   (if (< n 2)
       1
       (* n (factorial (- n 1)))))

(time (factorial 1000))
=> Execution took 0.012 s
     40…


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

Clojure的主页:

http://clojure.sourceforge.net/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值