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

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

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

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

(1..10)*.multiply(2)

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

(1..1000).sum()

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

def wordList = ['groovy', 'akka', 'grails framework', 'spock', 'typesafe']
def tweet = 'This is an example tweet talking about groovy and spock.'
wordList.any { word -> tweet.contains(word) }

4、读取文件

def fileText = new File('data.txt').text
def fileLines = new File('data.txt').readLines()

5、祝你生日快乐!

(1..4).each { println 'Happy Birthday ' + ((it == 3) ? 'dear Arturo' : 'to You') }

6. 过滤列表中的数值

def (passed, failed) = [49, 58, 76, 82, 88, 90].split{ it > 60 }

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

def results = new XmlSlurper().parse('http://search.twitter.com/search.atom?&q=groovy')

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

[14, 35, -7, 46, 98].min()
[14, 35, -7, 46, 98].max()

9. 并行处理

import groovyx.gpars.*
GParsPool.withPool { def result = dataList.collectParallel { processItem(it) } }

Gpars提供了直观安全的在Groovy里执行并行任务。

10. “Sieve of Eratosthenes”算法

def t = 2..100
(2..Math.sqrt(t.last())).each { n -> t -= ((2*n)..(t.last())).step(n) }
println t
分享这篇文章:

One Response to 震惊小伙伴的单行代码●Groovy篇

发表评论

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

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据