幾年前興起過一個“10個驚艷的XX單行代碼”的潮流。始作俑者好象是Marcus Kazmierczak的《10 Scala One Liners to Impress Your Friends》,然后出現(xiàn)了各種其它語言的版本。
我不是編程工作者,現(xiàn)在才看到那些文章,跟風(fēng)寫了個Mathematica版。不過很多功能在Mathematica里都可以直接用一個函數(shù)搞定,看起來不是那么驚艷。
需要Mathematica 10.1以上的版本。
1. 列表每項乘以2
Range[10] * 2
2. 列表求和
Fold[Plus, Range[1000]]
Total[Range[1000]]
3. 驗證字符串中是否存在某詞
wordList = {"coffeescript", "eko", "play framework", "and stuff", "falsy"}
tweet = "This is an example tweet talking about javascript and stuff."
StringContainsQ[tweet, wordList]
4. 讀取文件
fileText = Import["data.txt"]
fileLines = Import["data.txt", "List", "Numeric" -> False]
5. 生日歌
Do[Print["Happy Birthday " <> If[i == 3, "dear NAME", "to You"]], {i, 4}]
6. 過濾列表中的數(shù)字
{passed, failed} = Lookup[GroupBy[{49, 58, 76, 82, 88, 90}, # > 60 &], {True, False}, {}]
7. 讀取和分析XML Web service
results = Import["http://search.twitter.com/search.atom?&q=scala", "XML"]
8. 尋找列表中最大最小值
Min[{14, 35, -7, 46, 98}]
Max[{14, 35, -7, 46, 98}]
9. 并行處理
result = ParallelMap[processItem, dataList]
10. 埃拉托斯特尼篩法
Reap[Range[2, #] //. p : {x_, ___} :> Complement[p, Range[0, #, Sow[x]]]][[2, 1]] &