几年前,函数式编程的复兴正值巅峰,一篇介绍 Scala 中 10 个单行函数式代码的博文在网上走红。很快地,一系列使用其他语言实现这些单行代码的文章也随之出现,比如 Haskell, Ruby, Groovy, Clojure, Python, C#, F#, CoffeeScript。
每篇文章都令人印象深刻的揭示了这些语言中一些出色优秀的编程特征。编程高手们利用这些技巧提高编程速度、改进软件质量,编程初学者能从这些简洁的预防中学到各种编程语言的真谛。本《震惊小伙伴的单行代码系列》将逐一介绍这些各种编程语言单行代码文章,供大家学习参考。
1. 让列表中的每个元素都乘以2
#lists lapply(list(1:4),function(n){n*2}) # otherwise (1:4)*2
2. 求列表中的所有元素之和
#lists lapply(list(1:4),sum) # otherwise sum(unlist(list(1:4))) # or simply sum(1:4)
3. 判断一个字符串中是否存在某些词
wordlist = c("lambda", "data", "plot", "statistics", "R") tweet = c("R is an integrated suite of software facilities for data manipulation, calculation and graphical display") wordlist[wordlist %in% (c(unlist(strsplit(tweet,' ', fixed=T))))]
4. 读取文件
readLines("data.file", n=-1)
5. 祝你生日快乐!
lapply((1:4),function(x){ paste(c("Happy Birthday to ", ifelse(x!=3, "you", "dear Name")), sep="", collapse="")})
6. 过滤列表中的数值
n = c(49, 58, 76, 82, 88, 90); c(list(n[which(n<=60)]),list(n[which(n>60)]))
7. 获取XML web service数据并分析
library('XML'); xmlParseDoc('http://search.twitter.com/search.atom?&q=R-Project', asText=F)
8. 找到列表中最小或最大的一个数字
# for lists lapply(list(c(14, 35, -7, 46, 98)), min, classes="numeric", how="replace") # otherwise min(unlist(list(14, 35, -7, 46, 98))) # or simply min(c(14, 35, -7, 46, 98)) max(c(14, 35, -7, 46, 98))
9. 并行处理
# http://cran.r-project.org/web/packages/doSMP/vignettes/gettingstartedSMP.pdf # copy from Section 4 An example doSMP session library(doSMP); w <- startWorkers(workerCount = 4); registerDoSMP(w); foreach(i = 1:3) %dopar% sqrt(i)
10. “Sieve of Eratosthenes”算法
##ok, this one is a little cheating library('spuRs'); primesieve(c(),2:50)
不错,过来支持一下