Back to Home

10 “one-liners” that will impress your friends

scala · ruby · fsharp · coffeescript · clojure · python · csharp · haskell · single line · 10 · 42

10 “one-liners” that will impress your friends

    Over the past week, several topics appeared with the title “10 single-line per that will impress your friends ”, which contain a one-line solution to several simple tasks, demonstrating the advantages and“ coolness ”of the author’s favorite programming language. I decided to translate them and compile them in one topic for comparison. The whole wave began (sort of) with Scala.
    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.
    1. Double each item in the list.

      The function maptakes 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 functions reduceLeftand foldLeftthat return only one non-list value.
      (1 to 10) map { _ * 2 }
      In the commentary on the original article, an option was also suggested:
      (1 to 10) map (2*)

    2. Summarize all the numbers in the list.

      The most common use case reduceLeftis summing numbers in a list. This example sums numbers from 1 to 1000 using range functions toto create our sequence of numbers and reduceLeftto iterate and sum.
      (1 to 1000).reduceLeft( _ + _ )
      In the comments on the original article, the best option was proposed:
      (1 to 1000).sum

    3. Checking 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.
      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(_) ))
      In the comments on the original article, the best option was proposed:
      ...
      wordList.exists(tweet.contains(_))

    4. 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.toList

    5. Happy Birthday!

      A one-liner that displays the song “Hapy Birthday”. It illustrates the ternary operator Scala, as well as a combination of mapand foreach.
      (1 to 4).map { i => "Happy Birthday " + (if (i == 3) "dear NAME" else "to You") }.foreach { println }

    6. Number List Filtering

      Filter the list of numbers into two categories based on usage partition. 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 )

    7. 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")

    8. Search for the minimum (or maximum) in the list

      A couple more examples of use reduceLeftfor enumerating a list and applying a function.
      List(14, 35, -7, 46, 98).reduceLeft ( _ min _ )
      List(14, 35, -7, 46, 98).reduceLeft ( _ max _ )
      In the comments on the original article, the best option was proposed:
      List(14, 35, -7, 46, 98).min
      List(14, 35, -7, 46, 98).max

    9. Parallel processing

      In Scala 2.9 introduced a new type of collection called "parallel collection" using multi-core processors when performing bulk operations, such as foreach, 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))
      

    10. 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 .
      (n: Int) => (2 to n) |> (r => r.foldLeft(r.toSet)((ps, x) => if (ps(x)) ps -- (x * x to n by x) else ps))
      Requires the definition of the |> operator, the syntax of which is borrowed from F #. See, for example, Steve Gilham’s blog .
    Original post: “10 Scala One Liners to Impress Your Friends”
    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.

    1. Doubling all items in a list

      Marcus begins to show off with function map. We can do the same using rangeanonymous functions:
      [1..10].map (i) -> i*2
      but you can write in a more expressive form
      i * 2 for i in [1..10]

    2. Number List Amount

      Javascript (and CoffeeScript as its extension) also have built-in functions mapand reduce:
      [1..1000].reduce (t, s) -> t + s
      (reduce == reduceLeft, reduceRight is also available)

    3. Check for substring

      Very easy, since we have a method some. It returns true if any of the elements of the array is satisfied by a function:
      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
      But this will return the corresponding words:
      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.

    4. Read file

      Client-side JavaScript users are already familiar with this idea:
      fs.readFile 'data.txt', (err, data) -> fileText = data
      You can also use the synchronous version:
      fileText = fs.readFileSync('data.txt').toString()
      But in node.js, this is acceptable only for the application launch procedure. You must use the asynchronous version in your code.

    5. Happy Birthday

      Firstly, you can display the Scala version one to one:
      [1..4].map (i) -> console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You")
      But it is possible and better. This reads almost like pseudo-code:
      console.log "Happy Birthday #{if i is 3 then "dear Robert" else "to You"}" for i in [1..4]

    6. Number List Filtering

      Filtering the list of numbers turned out to be quite similar:
      passed = []
      failed = []
      (if score > 60 then passed else failed).push score for score in [49, 58, 76, 82, 88, 90]
      (You can still use filter, but then you won’t get a single line)

    7. 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 = body

    8. Search for the minimum (or maximum) in the list

      The function is convenient here apply. It allows you to call the function, passing the array as a list of arguments: Math.maxand Math.minget a variable number of arguments, i.e. Math.max 30, 10, 20returns 30. 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] # -7

    9. Parallel processing

      Пока что не существует. Вы можете создавать дочерние процессы и взаимодействовать с ними, или использовать WebWorkers API. Пропускаем.

    10. Решето Эратосфена

      Не удалось довести это до одной строки. Есть идеи?
      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
      Обновление (5 июня): @dionyziz прислал мне компактную версию:
      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

    11. Бонус

      Самая читаемая версия fizzbuzz, которую вы когда-либо видели:
      "#{if i%3 is 0 then 'fizz' else ''}#{if i%5 is 0 then 'buzz' else ''}" or i for i in [1..100]
      Ещё проще, но замудрённей, с небольшой подсказкой от satyr:
      ['fizz' unless i%3] + ['buzz' unless i%5] or i for i in [1..100]
    Оригинальный пост: «10 CoffeeScript One Liners to Impress Your Friends
    »

    Автор: Ricardo Tomasi



    F#


    In the spirit of 10 " 10 single-liners on Scala to impress your friends " here are some single-liners on F #:
    1. Doubling all numbers in a list

      It's simple, F # also has map:
      [1 .. 4] |> Seq.map (fun x -> x * x);;

    2. Number List Amount

      It is just as easy, since F # also has sum:
      [1 .. 4] |> Seq.sum;;

    3. Check for substring

      And it's simple, because we have find:
      ["f#"; "scala"] |> Seq.find(fun w -> "this tweet contains f#".Contains(w));;

    4. 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;;

    5. 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;;

    6. Filtering (actually splitting) lists

      Using the built-in function partition, we can easily split the list:
      [49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;

    7. XML parsing and parsing

      Опять же, пригодятся библиотеки .NET. К сожалению, это не совсем однострочник в F#. Но Дон Сайм показывает, как это сделать синхронно и асинхронно.

    8. Поиск максимума и минимума в списке

      Для этого в F# сеть строенные функции:
      [49; 58; 76; 82; 88; 90] |> Seq.min;;
      [49; 58; 76; 82; 88; 90] |> Seq.max;;

    9. Параллельная обработка

      Это пример от 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;;
    Оригинальный пост: «F# One liners to impress your friends»
    Автор: 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.
    1. Doubling all the numbers on the list

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

    2. Number List Amount

      (1..1000).inject { |sum, n| sum + n }
      Or using the (built-in) syntax Symbol#to_procthat has become available since Ruby version 1.8.7:
      (1..1000).inject(&:+)
      Or even like this:
      (1..1000).inject(:+)

    3. 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) }

    4. Reading files

      file_text = File.read("data.txt")
      file_lines = File.readlines("data.txt")
      The latter includes "\ n" at the end of each element of the array, which can be separated by adding .map { |str| str.chop }or using an alternative version:
      File.read("data.txt").split(/\n/)

    5. Happy Birthday

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

    6. Number List Filtering

      [49, 58, 76, 82, 88, 90].partition { |n| n > 60 }

    7. Retrieving and parsing XML from a web service

      require 'open-uri'
      require 'hpricot'
      results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala"))
      В этом примере требуются open-uri и hpricot или эквивалентные библиотеки, (вы можно использовать встроенную). Это не слишком много кода, но Скала явно выигрывает здесь.

    8. Поиск минимума (или максимума) в списке

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

    9. Параллельная обработка

      require 'parallel'
      Parallel.map(lots_of_data) do |chunk|
        heavy_computation(chunk)
      end
      В отличие от Scala, поддержка многоядерности не встроена. Этот пример требует parallel или аналогичный gem.

    10. Решето эратосфена

      Однострочник на Scala очень заумный, но совершенно нечитаемый. Простая реализация, требующая более чем одной строки, на Ruby:
      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
      Этот пример со StackOverflow.

    Оригинальный пост: «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 .
    1. Doubling all numbers in a list

      (map #(* % 2) (range 1 11))

    2. Number List Amount

      (reduce + (range 1 1001))

    3. Check for substring

      I find it proper to use regular expressions here:
      (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
      Как подсказали комментаторы, эта проблема может быть решена без использования регулярных выражений за счет использования множеств Clojure.
      (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

    4. Чтение файла

      (def file-text (slurp "data.txt")) ; Читает весь файл
      (def file-lines (clojure.contrib.io/read-lines "data.txt")) ; Читает последовательность строк
      Clojure Contrib будет считаться устаревшим в будущих релизах Clojure, clojure.contrib.io/read-lines можно записать в виде (line-seq (clojure.java.io/reader (clojure.java.io/file “data.txt”))) в Clojure 1.3 и старше. Спасибо Aaron за указание на это.

    5. С днём рожденья

      (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")))
      

    6. Фильтрация списка чисел

      (partition-by #(> % 60) [49 58 76 82 88 90])

    7. Получение и парсинг XML от веб-сервиса

      (clojure.xml/parse "http://search.twitter.com/search.atom?&q=clojure")

    8. Поиск минимума и максимума в списке

      (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]

    9. Параллельная обработка

      ;; Предположим, что process-line - это интенсивно использующая процессор функция, оперирующая со строками
      (pmap process-line lines) ; Обратите внимание на "p" перед map

    10. Решето Эратосфена

      Я не достаточно хорош (с точки зрения производительности и красоты) для однострочного решения «Решета Эратосфена». Я рекомендую проверить труд Кристофа Гранда на эту тему под названием «Все любят Решето Эратосфена» для решения этой проблемы.

    11. Решение FizzBuzz

      (map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 3)) "Fizz" (zero? (mod % 5)) "Buzz" :else %) (range 1 101))
    Original post: “10 Clojure One Liners to Impress Your Friends”
    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.
    1. Doubling all numbers in a list

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

    2. Number List Amount

      print sum(range(1,1001))

    3. 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)

    4. Read file

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

    5. Happy Birthday

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

    6. 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],([],[]))

    7. 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")

    8. Search for minimum and maximum in the list

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

    9. Parallel processing

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

    10. 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))))
    Original post: "10 Python one liners to impress your friends"
    Posted by Dhananjay Nene



    C #


    1. Doubling all numbers in a list
      Print("Multiple each item in a list by 2", Enumerable.Range(1, 10).Select(i => i * 2));

    2. Number List Amount

      Print("Sum a list of numbers", Enumerable.Range(1, 1000).Sum());

    3. 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));

    4. Read file

      Print("Read in a File", File.ReadAllBytes("oneliners.exe").Length);

    5. Happy Birthday

      Print("Happy Birthday", Enumerable.Range(1, 4).Select((i) => string.Format("Happy Birthday {0} ", i == 3 ? "dear NAME" : "to You")));

    6. 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);

    7. 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"));

    8. 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 }));

    9. Parallel processing

      Print("Parallel Processing", Enumerable.Range(1, 10).AsParallel().Select((i)=>i*2).AsEnumerable());

    10. Fizzbuzz

      Print("Fizzbuzz", Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":"")));
    Original post: “10 C # One Liners to Impress Your Friends”
    Posted by Richard Birkby



    Haskell


    Following the meme ( scala , ruby , clojure , python , f # , coffeescript , c # ).

    1. Doubling all numbers in a list
      map (*2) [1..10]

    2. Number List Amount

      foldl (+) 0 [1..1000]
      -- или лучше
      sum [1..1000]

    3. 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) wordlist

    4. Read file

      fileText <- readFile "data.txt"
      let fileLines = lines fileText
      -- или лучше
      let fileLines = fmap lines $ readFile "data.txt"

    5. Happy Birthday

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

    6. Number List Filtering

      let (passed, failed) = partition (>60) [49, 58, 76, 82, 88, 90]

    7. Retrieving and parsing XML from a web service

      For this example, you need packages curland xml. 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" []

    8. 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]

    9. Parallel processing

      A package is needed for this example parallel.
      import Control.Parallel
      import Control.Parallel.Strategies
      parMap rseq (*2) [1..100]

    10. Prime Generation

      let pgen (p:xs) = p : pgen [x|x <- xs, x `mod` p > 0]
      take 40 (pgen [2..])
    Original post: “10 Haskell One Liners to Impress Your Friends”
    Posted by Michael Fogus




    And now your options, and may the holivars begin! )

    Read Next