Jun 09

## 10 XXX One Liners to Impress Your Friends

one-liners scala ruby coffeescript python haskell

There is some fascination to solve problems by writing as little code as possible. And even yesterday I visited the Rails Usergroup Hamburg where we played Ruby Golf.

It's a great way to learn some not so common constructs of the language of your choice. Even if some of them don't even try to be very expressive or elegant. But there's always something you can learn from, right?

Last week there came up interesting posts to show you '10 XXX One Liners to Impress Your Friends'. So let's put some Scala/Ruby/CoffeeScript/Python/Haskell side by side. But please don't judge a language by these examples. It's more an inspiration.

At the end of this article you'll find a list of all original posts the code cames from. Have fun!

### 1. Multiple Each Item in a List by 2

Scala

``````  (1 to 10) map { _ * 2 }
``````

Ruby

``````  (1..10).map { |n| n * 2 }
``````

CoffeeScript

``````  [1..10].map (i) -&gt; i*2

OR

i * 2 for i in [1..10]
``````

Python

``````  print map(lambda x: x * 2, range(1,11))
``````

``````  map (*2) [1..10]
``````

### 2. Sum a List of Numbers

Scala

``````  (1 to 1000).reduceLeft( _ + _ )
``````

Ruby

``````  (1..1000).inject { |sum, n| sum + n }

OR

(1..1000).inject(&amp;:+)

OR

(1..1000).inject(:+)
``````

CoffeeScript

``````  [1..1000].reduce (t, s) -&gt; t + s
``````

Python

``````  print sum(range(1,1001))
``````

``````  foldl (+) 0 [1..1000]

OR

sum [1..1000]
``````

### 3. Verify if Exists in a String

Scala

``````  val wordlist = List("scala", "akka", "play framework", "sbt", "typesafe")
val tweet = "This is an example tweet talking about scala and sbt."
(words.foldLeft(false)( _ || tweet.contains(_) ))
``````

Ruby

``````  words = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."
words.any? { |word| tweet.include?(word) }
``````

CoffeeScript

``````  wordList = ["coffeescript", "eko", "play framework", "and stuff", "falsy"]
tweet = "This is an example tweet talking about javascript and stuff."
wordList.some (word) -&gt; ~tweet.indexOf word
``````

Python

``````  wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."
print map(lambda x: x in tweet.split(),wordlist)
``````

``````  import Data.List
let wordlist = ["monad", "monoid", "Galois", "ghc", "SPJ"]
let tweet = "This is an example tweet talking about SPJ interviewing with Galois"
or \$ map (flip isInfixOf tweet) wordlist

OR

any (flip isInfixOf tweet) wordlist
``````

### 4. Read in a File

Scala

``````  val fileText = io.Source.fromFile("data.txt").mkString
val fileLines = io.Source.fromFile("data.txt").getLines.toList
``````

Ruby

``````  file_text = File.read("data.txt")
``````

CoffeeScript

``````  fs.readFile 'data.txt', (err, data) -&gt; fileText = data

OR (sync)

``````

Python

``````  print open("ten_one_liners.py").readlines()
``````

``````  fileText &lt;- readFile "data.txt"
let fileLines = lines fileText

OR

let fileLines = fmap lines \$ readFile "data.txt"
``````

### 5. Happy Birthday to You!

Scala

``````  (1 to 4).map { i =&gt; "Happy Birthday " + (if (i == 3) "dear NAME" else "to You") }.foreach { println }
``````

Ruby

``````  4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }
``````

CoffeeScript

``````  [1..4].map (i) -&gt; console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You")

OR

console.log "Happy Birthday #{if i is 3 then "dear Robert" else "to You"}" for i in [1..4]
``````

Python

``````  print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))
``````

``````  mapM_ putStrLn ["Happy Birthday " ++ (if x == 3 then "dear NAME" else "to You") | x &lt;- [1..4]]
``````

### 6. Filter list of numbers

Scala

``````  val (passed, failed) = List(49, 58, 76, 82, 88, 90) partition ( _ &gt; 60 )
``````

Ruby

``````  [49, 58, 76, 82, 88, 90].partition { |n| n &gt; 60 }
``````

CoffeeScript

``````  passed = []
failed = []
(if score &gt; 60 then passed else failed).push score for score in [49, 58, 76, 82, 88, 90]
``````

Python

``````  print reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
``````

``````  let (passed, failed) = partition (&gt;60) [49, 58, 76, 82, 88, 90]
``````

### 7. Fetch and Parse an XML web service

Scala

``````  val results = XML.load("http://search.twitter.com/search.atom?&amp;q=scala")
``````

Ruby

``````  require 'open-uri'
require 'hpricot'
``````

CoffeeScript

``````  request.get { uri:'path/to/api.json', json: true }, (err, r, body) -&gt; results = body
``````

Python

``````  from xml.dom.minidom import parse, parseString
import urllib2
``````

``````  import Network.Curl
import Text.XML.Light

OR

Control.Applicative
``````

### 8. Find minimum (or maximum) in a List

Scala

``````  List(14, 35, -7, 46, 98).reduceLeft ( _ min _ )
List(14, 35, -7, 46, 98).reduceLeft ( _ max _ )
``````

Ruby

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

CoffeeScript

``````  Math.max.apply @, [14, 35, -7, 46, 98]
Math.min.apply @, [14, 35, -7, 46, 98]
``````

Python

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

``````  foldl1 min [14, 35, -7, 46, 98]
foldl1 max [14, 35, -7, 46, 98]

OR

minimum [14, 35, -7, 46, 98]
maximum [14, 35, -7, 46, 98]
``````

### 9. Parallel Processing

Scala

``````  val result = dataList.par.map(line =&gt; processItem(line))
``````

Ruby

``````  require 'parallel'

Parallel.map(lots_of_data) do |chunk|
heavy_computation(chunk)
end
``````

CoffeeScript

``````  SKIP
``````

Python

``````  import multiprocessing
import math

print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
``````

``````  import Control.Parallel
import Control.Parallel.Strategies

parMap rseq (*2) [1..100]
``````

### 10. Sieve of Eratosthenes

Scala

``````  (n: Int) =&gt; (2 to n) |&gt; (r =&gt; r.foldLeft(r.toSet)((ps, x) =&gt; if (ps(x)) ps -- (x * x to n by x) else ps))
``````

Ruby

``````  index = 0
while primes[index]**2 &lt;= primes.last
prime = primes[index]
primes = primes.select { |x| x == prime || x % prime != 0 }
index += 1
end
p primes
``````

CoffeeScript

``````  sieve = (num) -&gt;
numbers = [2..num]
while ((pos = numbers[0]) * pos) &lt;= num
delete numbers[i] for n, i in numbers by pos
numbers.shift()
numbers.indexOf(num) &gt; -1
``````

Python

``````  print sorted(set(range(2,n+1)).difference(set((p * f) for p in range(2,int(n**0.5) + 2) for f in range(2,(n/p)+1))))
``````

``````  let pgen (p:xs) = p : pgen [x|x &lt;- xs, x `mod` p &gt; 0]