10 “one-liners” that will impress your friends
So let's go!
Scala
These are 10 one-liners demonstrating the power of the Scala language to impress your friends and maybe even women :). They are also great examples of using functional programming and Scala syntax, which you may not be familiar with. I think that there is no better way to study it than to see real examples.
Double each item in the list.
The functionmaptakes each element of the list and applies the corresponding function to it. In this example, we take each element and multiply it by 2. As a result, a list of the same size will be returned, unlike other examples that use functionsreduceLeftandfoldLeftthat return only one non-list value.
In the commentary on the original article, an option was also suggested:(1 to 10) map { _ * 2 }(1 to 10) map (2*)Summarize all the numbers in the list.
The most common use casereduceLeftis summing numbers in a list. This example sums numbers from 1 to 1000 using range functionstoto create our sequence of numbers andreduceLeftto iterate and sum.
In the comments on the original article, the best option was proposed:(1 to 1000).reduceLeft( _ + _ )(1 to 1000).sumChecking the occurrence of a substring
This example returns a Boolean value if a word from the list is on the specified string. I used this example to verify that the tweet contains the word that interests me. Yes, technically these are three lines, but the first two are just a job of variables.
In the comments on the original article, the best option was proposed: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(_) ))... wordList.exists(tweet.contains(_))Read from file
This example can be impressive against the background of Java, it is a pretty general example of reading a file in one line. There are actually two examples here: one reads the entire file into a string, the other reads the file line by line into the list.val fileText = io.Source.fromFile("data.txt").mkString val fileLines = io.Source.fromFile("data.txt").getLines.toListHappy Birthday!
A one-liner that displays the song “Hapy Birthday”. It illustrates the ternary operator Scala, as well as a combination ofmapandforeach.(1 to 4).map { i => "Happy Birthday " + (if (i == 3) "dear NAME" else "to You") }.foreach { println }Number List Filtering
Filter the list of numbers into two categories based on usagepartition. In this example, two student lists are created based on the results of their testing.val (passed, failed) = List(49, 58, 76, 82, 88, 90) partition ( _ > 60 )Retrieving and parsing XML from a web service
Since XML is Scala's native framework, XML parsing is effortless. Here is an example of retrieving a Twitter search feed.val results = XML.load("http://search.twitter.com/search.atom?&q=scala")Search for the minimum (or maximum) in the list
A couple more examples of usereduceLeftfor enumerating a list and applying a function.
In the comments on the original article, the best option was proposed:List(14, 35, -7, 46, 98).reduceLeft ( _ min _ ) List(14, 35, -7, 46, 98).reduceLeft ( _ max _ )List(14, 35, -7, 46, 98).min List(14, 35, -7, 46, 98).maxParallel processing
In Scala 2.9 introduced a new type of collection called "parallel collection" using multi-core processors when performing bulk operations, such asforeach,map,filteretc ... Here a video of Alexander Prokopets on parallel collections at the Scala Days 2010.
This example illustrates the use of parallel collections. Imagine that you have a lot of data defined in the dataList list and the processItem function that uses the processor very heavily. The following one-liner gives you parallel list processing.val result = dataList.par.map(line => processItem(line))Sieve of Eratosthenes
Well, this time the example is not entirely practical and, technically, not one-line, because it relies on the operator defined earlier, but it’s still damn cool, even if it’s not readable. Daniel Sobral wrote an implementation of the Sieve of Eratosthenes algorithm, which is used to determine if a number is prime .
Requires the definition of the |> operator, the syntax of which is borrowed from F #. See, for example, Steve Gilham’s blog .(n: Int) => (2 to n) |> (r => r.foldLeft(r.toSet)((ps, x) => if (ps(x)) ps -- (x * x to n by x) else ps))
Posted by Marcus Kazmierczak
CoffeScript
You may have read the post “ 10 Single Line at Scala to Impress Your Friends ” on the Marcus Kazmierczak blog recently posted on HN . Although I don’t know Scala (or Java), but it looks great, so I decided to impress my friends too - some are switching from Java to Scala, we go from Javascript to CoffeeScript. We will use node.js as an environment to run all the examples.
Doubling all items in a list
Marcus begins to show off with functionmap. We can do the same usingrangeanonymous functions:
but you can write in a more expressive form[1..10].map (i) -> i*2i * 2 for i in [1..10]Number List Amount
Javascript (and CoffeeScript as its extension) also have built-in functionsmapandreduce:
(reduce == reduceLeft, reduceRight is also available)[1..1000].reduce (t, s) -> t + sCheck for substring
Very easy, since we have a methodsome. It returns true if any of the elements of the array is satisfied by a function:
But this will return the corresponding words:wordList = ["coffeescript", "eko", "play framework", "and stuff", "falsy"] tweet = "This is an example tweet talking about javascript and stuff." wordList.some (word) -> ~tweet.indexOf word
"wordList.filter (word) -> ~tweet.indexOf word~" Is not a special operator in CoffeeScript, but just a dirty trick. This is the bitwise NOT operator, which inverts the bits of its operand. In practice, this equates to-x-1. Here it works on the basis that we want to do a check for the index more than-1, and-(-1)-1 == 0evaluates to false.Read file
Client-side JavaScript users are already familiar with this idea:
You can also use the synchronous version:fs.readFile 'data.txt', (err, data) -> fileText = data
But in node.js, this is acceptable only for the application launch procedure. You must use the asynchronous version in your code.fileText = fs.readFileSync('data.txt').toString()Happy Birthday
Firstly, you can display the Scala version one to one:
But it is possible and better. This reads almost like pseudo-code:[1..4].map (i) -> console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You")console.log "Happy Birthday #{if i is 3 then "dear Robert" else "to You"}" for i in [1..4]Number List Filtering
Filtering the list of numbers turned out to be quite similar:
(You can still use filter, but then you won’t get a single line)passed = [] failed = [] (if score > 60 then passed else failed).push score for score in [49, 58, 76, 82, 88, 90]Retrieving and parsing XML from a web service
XML what? I have not heard about this. Let's get JSON instead:request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = bodySearch for the minimum (or maximum) in the list
The function is convenient hereapply. It allows you to call the function, passing the array as a list of arguments:Math.maxandMath.minget a variable number of arguments, i.e.Math.max 30, 10, 20returns30. Let's try to work with an array:Math.max.apply @, [14, 35, -7, 46, 98] # 98 Math.min.apply @, [14, 35, -7, 46, 98] # -7Parallel processing
Пока что не существует. Вы можете создавать дочерние процессы и взаимодействовать с ними, или использовать WebWorkers API. Пропускаем.Решето Эратосфена
Не удалось довести это до одной строки. Есть идеи?
Обновление (5 июня): @dionyziz прислал мне компактную версию:sieve = (num) -> numbers = [2..num] while ((pos = numbers[0]) * pos) <= num delete numbers[i] for n, i in numbers by pos numbers.shift() numbers.indexOf(num) > -1
которую мы можем использовать для действительно однострочной версии, похожей на оригинал:primes = [] primes.push i for i in [2..100] when not (j for j in primes when i % j == 0).length
Или несколько более эффективно:(n) -> (p.push i for i in [2..n] when not (j for j in (p or p=[]) when i%j == 0)[0]) and n in p(n) -> (p.push i for i in [2..n] when !(p or p=[]).some((j) -> i%j is 0)) and n in pБонус
Самая читаемая версияfizzbuzz, которую вы когда-либо видели:
Ещё проще, но замудрённей, с небольшой подсказкой от satyr:"#{if i%3 is 0 then 'fizz' else ''}#{if i%5 is 0 then 'buzz' else ''}" or i for i in [1..100]['fizz' unless i%3] + ['buzz' unless i%5] or i for i in [1..100]
»
Автор: Ricardo Tomasi
F#
In the spirit of 10 " 10 single-liners on Scala to impress your friends " here are some single-liners on F #:
Doubling all numbers in a list
It's simple, F # also hasmap:[1 .. 4] |> Seq.map (fun x -> x * x);;Number List Amount
It is just as easy, since F # also hassum:[1 .. 4] |> Seq.sum;;Check for substring
And it's simple, because we havefind:["f#"; "scala"] |> Seq.find(fun w -> "this tweet contains f#".Contains(w));;Reading a file (boring!)
F # has all the libraries. NET It is very easy to read all the lines of a file as a sequence:File.ReadLines(@"file.txt") |> Seq.map(fun l -> l.Length) |> Seq.sum;;Happy Birthday!
Boring too ... like this:[1 .. 4] |> Seq.map (fun i -> "Happy Birthday " + (if i = 3 then "dear NAME" else "to you")) |> Seq.iter Console.WriteLine;;Filtering (actually splitting) lists
Using the built-in functionpartition, we can easily split the list:[49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;XML parsing and parsing
Опять же, пригодятся библиотеки .NET. К сожалению, это не совсем однострочник в F#. Но Дон Сайм показывает, как это сделать синхронно и асинхронно.Поиск максимума и минимума в списке
Для этого в F# сеть строенные функции:[49; 58; 76; 82; 88; 90] |> Seq.min;; [49; 58; 76; 82; 88; 90] |> Seq.max;;Параллельная обработка
Это пример от J Rocha. Предположим, у нас есть метод «isprime», и мы хотим получить количество простых чисел, сгруппированных по их последней цифре, от 1 до 50000. PSeq обрабатывает последовательности параллельно:[|1 .. 50000|] |> PSeq.filter isprime |> PSeq.groupBy (fun i -> i % 10) |> PSeq.map (fun (k, vs) -> (k, Seq.length vs)) |> Seq.toArray |> Seq.sort |> Seq.toList;;
Автор: Will Fitzgerald
Ruby
A list of 10 single-line examples has been published to show the expressiveness of Scala. The CoffeeScript version appeared quickly, so I thought I published the Ruby version alone. I find the Ruby syntax a little cleaner than Scala, but in essence (at least as far as these examples show) is relatively similar.
Doubling all the numbers on the list
(1..10).map { |n| n * 2 }Number List Amount
Or using the (built-in) syntax(1..1000).inject { |sum, n| sum + n }Symbol#to_procthat has become available since Ruby version 1.8.7:
Or even like this:(1..1000).inject(&:+)(1..1000).inject(:+)Check for substring
words = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." words.any? { |word| tweet.include?(word) }Reading files
The latter includes "\ n" at the end of each element of the array, which can be separated by addingfile_text = File.read("data.txt") file_lines = File.readlines("data.txt").map { |str| str.chop }or using an alternative version:File.read("data.txt").split(/\n/)Happy Birthday
4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }Number List Filtering
[49, 58, 76, 82, 88, 90].partition { |n| n > 60 }Retrieving and parsing XML from a web service
В этом примере требуются open-uri и hpricot или эквивалентные библиотеки, (вы можно использовать встроенную). Это не слишком много кода, но Скала явно выигрывает здесь.require 'open-uri' require 'hpricot' results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala"))Поиск минимума (или максимума) в списке
[14, 35, -7, 46, 98].min [14, 35, -7, 46, 98].maxПараллельная обработка
В отличие от Scala, поддержка многоядерности не встроена. Этот пример требует parallel или аналогичный gem.require 'parallel' Parallel.map(lots_of_data) do |chunk| heavy_computation(chunk) endРешето эратосфена
Однострочник на Scala очень заумный, но совершенно нечитаемый. Простая реализация, требующая более чем одной строки, на Ruby:
Этот пример со StackOverflow.index = 0 while primes[index]**2 <= primes.last prime = primes[index] primes = primes.select { |x| x == prime || x % prime != 0 } index += 1 end p primes
Оригинальный пост: «10 Ruby One Liners to Impress Your Friends»
Автор: Antonio Cangiano
Clojure
I saw an interesting post today called “ 10 Single-Line on Scala to Impress Your Friends, ” and then someone posted on another blog post entitled “ 10 Single-Line on CoffeeScript to Impress Your Friends ”. These two posts show small tasks (most of them have trivial solutions in modern programming languages), each of which is executed in approximately 1 line of code.
I think it would be appropriate to do the same for my favorite programming language - Clojure .
Doubling all numbers in a list
(map #(* % 2) (range 1 11))Number List Amount
(reduce + (range 1 1001))Check for substring
I find it proper to use regular expressions here:
Как подсказали комментаторы, эта проблема может быть решена без использования регулярных выражений за счет использования множеств Clojure.(def tweet "This is an example tweet talking about clojure and emacs.") (def regex (re-pattern (apply str (interpose "|" ["clojure" "logic" "compojure" "emacs" "macros"])))) (re-seq regex tweet) ; Возвращает сами совпадения, а не true/false(def tweet "This is an example tweet talking about clojure and emacs.") (def is-word? (set ["clojure" "logic" "compojure" "emacs" "macros"])) (not (nil? (some is-word? (.split tweet " ")))) ; Возвращает true/falseЧтение файла
Clojure Contrib будет считаться устаревшим в будущих релизах Clojure,(def file-text (slurp "data.txt")) ; Читает весь файл (def file-lines (clojure.contrib.io/read-lines "data.txt")) ; Читает последовательность строкclojure.contrib.io/read-linesможно записать в виде(line-seq (clojure.java.io/reader (clojure.java.io/file “data.txt”)))в Clojure 1.3 и старше. Спасибо Aaron за указание на это.С днём рожденья
Альтернативная версия:(doseq [l (map #(str "Happy Birthday " (if (= % 2) "dear Rich" "to You")) (range 4))] (println l))(dotimes [n 4] (println "Happy Birthday " (if (= n 2) "dear Rich" "to You")))Фильтрация списка чисел
(partition-by #(> % 60) [49 58 76 82 88 90])Получение и парсинг XML от веб-сервиса
(clojure.xml/parse "http://search.twitter.com/search.atom?&q=clojure")Поиск минимума и максимума в списке
(reduce max [14 35 -7 46 98]) (reduce min [14 35 -7 46 98]) ;; И теперь оба сразу ((juxt #(reduce max %) #(reduce min %)) [14 35 -7 46 98]) ; Возвращает [98 -7]Параллельная обработка
;; Предположим, что process-line - это интенсивно использующая процессор функция, оперирующая со строками (pmap process-line lines) ; Обратите внимание на "p" перед mapРешето Эратосфена
Я не достаточно хорош (с точки зрения производительности и красоты) для однострочного решения «Решета Эратосфена». Я рекомендую проверить труд Кристофа Гранда на эту тему под названием «Все любят Решето Эратосфена» для решения этой проблемы.Решение FizzBuzz
(map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 3)) "Fizz" (zero? (mod % 5)) "Buzz" :else %) (range 1 101))
Posted by Baishampayan
Python
After 10 amazing single-liners in Scala / Ruby / Clojure / CoffeeScript, I thought it would be interesting to do the same in Python.
Without much noise ... let's go. Note that variable declarations and imports are on separate lines as needed. Also, each line is written so that the result is output to standard output for quick verification.
This post is probably one of the fastest that I wrote.
Doubling all numbers in a list
print map(lambda x: x * 2, range(1,11))Number List Amount
print sum(range(1,1001))Check for substring
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)Read file
print open("ten_one_liners.py").readlines()Happy Birthday
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))Number List Filtering
print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))Retrieving and parsing XML from a web service
from xml.dom.minidom import parse, parseString import urllib2 # note - i convert it back into xml to pretty print it print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")Search for minimum and maximum in the list
print min([14, 35, -7, 46, 98]) print max([14, 35, -7, 46, 98])Parallel processing
import multiprocessing import math print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))Sieve of Eratosthenes
n = 50 # Мы получим простые числа между 2 и 50 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))))
Posted by Dhananjay Nene
C #
Doubling all numbers in a list
Print("Multiple each item in a list by 2", Enumerable.Range(1, 10).Select(i => i * 2));Number List Amount
Print("Sum a list of numbers", Enumerable.Range(1, 1000).Sum());Check for substring
var wordlist = new[] { "C#", "and stuff" }; var tweet = "This is an example tweet talking about C# and stuff"; Print("Verify if a word exists in string", wordlist.Any(word => tweet.IndexOf(word) > -1)); Print("Show matched words in string", wordlist.Where(word => tweet.IndexOf(word) > -1));Read file
Print("Read in a File", File.ReadAllBytes("oneliners.exe").Length);Happy Birthday
Print("Happy Birthday", Enumerable.Range(1, 4).Select((i) => string.Format("Happy Birthday {0} ", i == 3 ? "dear NAME" : "to You")));Number List Filtering
var passed = new List(); var failed = new List (); (from bucket in new[] { passed, failed } from i in new[] { 49, 58, 76, 82, 88, 90 } select new { bucket, i }).ToList().ForEach((tuple) => tuple.bucket.AddRange(Enumerable.Repeat(tuple, 1).Where((tup) => (tup.bucket == passed && tup.i > 60) || (tup.bucket == failed && tup.i <= 60)).Select((tup) => tup.i))); Print("Filter list of numbers >60", (IEnumerable )passed); Print("Filter list of numbers <=60", (IEnumerable )failed); Retrieving and parsing XML from a web service
Print("Fetch and Parse an XML web service", XDocument.Load("http://search.twitter.com/search.atom?&q=scala"));Search for minimum and maximum in the list
Print("Find minimum in a list", Enumerable.Min(new[] { 14, 35, -7, 46, 98 })); Print("Find maximum in a list", Enumerable.Max(new[] { 14, 35, -7, 46, 98 }));Parallel processing
Print("Parallel Processing", Enumerable.Range(1, 10).AsParallel().Select((i)=>i*2).AsEnumerable());Fizzbuzz
Print("Fizzbuzz", Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":"")));
Posted by Richard Birkby
Haskell
Following the meme ( scala , ruby , clojure , python , f # , coffeescript , c # ).
Doubling all numbers in a list
map (*2) [1..10]Number List Amount
foldl (+) 0 [1..1000] -- или лучше sum [1..1000]Check for substring
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 -- или лучше any (flip isInfixOf tweet) wordlistRead file
fileText <- readFile "data.txt" let fileLines = lines fileText -- или лучше let fileLines = fmap lines $ readFile "data.txt"Happy Birthday
mapM_ putStrLn ["Happy Birthday " ++ (if x == 3 then "dear NAME" else "to You") | x <- [1..4]]Number List Filtering
let (passed, failed) = partition (>60) [49, 58, 76, 82, 88, 90]Retrieving and parsing XML from a web service
For this example, you need packagescurlandxml. See RWH for their installation.import Network.Curl import Text.XML.Light import Control.Monad let results = liftM parseXMLDoc $ liftM snd (curlGetString "http://search.twitter.com/search.atom?&q=haskell" []) -- или лучше Control.Applicative let results = parseXMLDoc . snd <$> curlGetString "http://search.twitter.com/search.atom?&q=haskell" []Search for minimum and maximum in the list
foldl1 min [14, 35, -7, 46, 98] foldl1 max [14, 35, -7, 46, 98] -- или лучше minimum [14, 35, -7, 46, 98] maximum [14, 35, -7, 46, 98]Parallel processing
A package is needed for this exampleparallel.import Control.Parallel import Control.Parallel.Strategies parMap rseq (*2) [1..100]Prime Generation
let pgen (p:xs) = p : pgen [x|x <- xs, x `mod` p > 0] take 40 (pgen [2..])
Posted by Michael Fogus
And now your options,