📜 ⬆️ ⬇️

10 "one-liners" that will impress your friends

Over the past week, several topics have appeared with the name “10 one-line players on <MY_LANGUAGE>, which will impress your friends”, which contain a single-line solution to several simple tasks, demonstrating the merits and “coolness” of the author's favorite programming language. I decided to translate them and put 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 :). In addition, they are excellent examples of the use of functional programming and the syntax of the Scala language, which you may not be familiar with. I think there is no better way to study it than to see real examples.
  1. We double each element of the list

    The map function takes 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 the reduceLeft and foldLeft , which return only one non-list value.
     (1 to 10) map { _ * 2 } 
    In the commentary to the original article, a variant was also proposed:
     (1 to 10) map (2*) 

  2. Sum all the numbers in the list

    The most common use of reduceLeft is to add numbers in a list. In this example, numbers from 1 to 1000 are summed using the range to functions to create our sequence of numbers and reduceLeft for iteration and summation.
     (1 to 1000).reduceLeft( _ + _ ) 
    In the comments to the original article the best option was proposed:
     (1 to 1000).sum 

  3. Check the occurrence of a substring

    This example returns a boolean value if a word from the list is included in the specified string. I used this example to check that the tweet contains the word that interests me. Yes, technically these are three lines, but the first two are just the task 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 to the original article the best option was proposed:
     ... wordList.exists(tweet.contains(_)) 

  4. Reading from file

    This example can be impressive against the background of Java, this is a fairly general example of reading a file in one line. In fact, here are two examples: 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!

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

  6. Filtering a list of numbers

    Filtering the list of numbers into two categories based on the use of a partition . In this example, two lists of students are created based on the results of their testing.
     val (passed, failed) = List(49, 58, 76, 82, 88, 90) partition ( _ > 60 ) 

  7. Receiving and parsing XML from a web service

    Since XML is Scala's native structure, XML parsing happens without any effort. 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 a minimum (or maximum) in the list

    A couple more examples of using reduceLeft to iterate through the list and use a function.
     List(14, 35, -7, 46, 98).reduceLeft ( _ min _ ) List(14, 35, -7, 46, 98).reduceLeft ( _ max _ ) 
    In the comments to 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, a new type of collection called “parallel collections” was introduced using multi-core processors when performing bulk operations, such as foreach , map , filter , etc ... Here is a video from Alexander Prokopets about parallel collections on 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 is very processor intensive. The following lineup gives you a 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, since it relies on the operator defined earlier, but it is still pretty damn cool, even if not readable. Daniel Sobral wrote an implementation of the Sieve of Eratosthenes algorithm, which is used to determine whether a number is simple .
     (n: Int) => (2 to n) |> (r => r.foldLeft(r.toSet)((ps, x) => if (ps(x)) ps -- (x * x to n by x) else ps)) 
    It requires the definition of the operator |>, whose syntax is borrowed from F #. See, for example, on 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 Scala line- ups to impress your friends ” on the Marcus Kazmierczak blog, recently posted on HN . Although I do not know Scala (or Java), but it looks great, so I also decided to impress my friends - some are switching from Java to Scala, we are moving from Javascript to CoffeeScript. We will use node.js as the environment to run all the examples.

  1. Doubling all items in the list

    Marcus starts bragging with the map function. We can do the same thing using range and an anonymous function:
     [1..10].map (i) -> i*2 
    but you can write in a more expressive way
     i * 2 for i in [1..10] 

  2. The sum of the list of numbers

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

  3. Substring occurrence check

    Very easy, since we have some method. It returns true if the function satisfies any of the array elements:
     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 
    This will return the corresponding words:
     wordList.filter (word) -> ~tweet.indexOf word 
    " ~ " Is not a special operator in CoffeeScript, but simply a dirty trick. This is a bitwise NOT operator that inverts the bits of its operand. In practice, this equates to -x-1 . Here it works based on what we want to do to check for an index greater than -1 , and -(-1)-1 == 0 is evaluated as false.

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

    First, you can display the Scala version of one to one:
     [1..4].map (i) -> console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You") 
    But it can be better. It 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. Filtering a list of numbers

    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 the filter, but then you will not get a one-liner)

  7. Receiving and parsing XML from a web service

    XML what? I have not heard of this. Let's get JSON instead:
     request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body 

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

    The function apply convenient here. It allows you to call a function by passing an array as a list of arguments: Math.max and Math.min receive a variable number of arguments, i.e. Math.max 30, 10, 20 returns 30 . Let's try to work with the array:
     Math.max.apply @, [14, 35, -7, 46, 98] # 98 Math.min.apply @, [14, 35, -7, 46, 98] # -7 

  9. Parallel processing

    Not yet exist. You can create child processes and interact with them, or use the WebWorkers API . We skip it.

  10. Sieve of Eratosthenes

    Could not bring this to a single line. Any ideas?
     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 
    Update (June 5): @dionyziz sent me a compact version:
     primes = [] primes.push i for i in [2..100] when not (j for j in primes when i % j == 0).length 
    which we can use for a really single line version, similar to the original:
     (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 
    Or a little more efficiently:
     (n) -> (p.push i for i in [2..n] when !(p or p=[]).some((j) -> i%j is 0)) and n in p 

  11. Bonus

    The most widely read fizzbuzz version you have ever seen:
     "#{if i%3 is 0 then 'fizz' else ''}#{if i%5 is 0 then 'buzz' else ''}" or i for i in [1..100] 
    Even simpler, but more sophisticated, with a little hint from satyr :
     ['fizz' unless i%3] + ['buzz' unless i%5] or i for i in [1..100] 
Original post: "10 CoffeeScript One Liners to Impress Your Friends
"
Posted by: Ricardo Tomasi


F #


In the spirit of 10 " Scala's 10 one-liners to impress your friends ", here are some F # one-liners:
  1. Doubling all numbers in the list

    Everything is simple, F # also has a map :
     [1 .. 4] |> Seq.map (fun x -> x * x);; 

  2. The sum of the list of numbers

    This is as simple as F # has a sum :
     [1 .. 4] |> Seq.sum;; 

  3. Substring occurrence check

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

  4. Reading a file (duly!)

    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!

    Also boring ... 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, separating) lists

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

  7. Getting and parsing XML

    Again, useful .NET libraries. Unfortunately, this is not exactly one line in F #. But Don Syme shows how to do this synchronously and asynchronously .

  8. Search for high and low in the list

    To do this, the F # network has built-in functions:
     [49; 58; 76; 82; 88; 90] |> Seq.min;; [49; 58; 76; 82; 88; 90] |> Seq.max;; 

  9. Parallel processing

    This is an example from J Rocha . Suppose we have the “isprime” method, and we want to get the number of prime numbers, grouped by their last digit, from 1 to 50,000. PSeq processes sequences in parallel:
     [|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;; 
Original post: "F # One liners to impress your friends"
By: Will Fitzgerald


Ruby


A list of 10 single-line examples was published, which are designed to show the expressiveness of Scala. The CoffeeScript version appeared quickly, so I thought I published the Ruby version one. I find the Ruby syntax a bit cleaner than Scala, but in essence (at least as far as these examples show) is relatively similar.
  1. Doubling all the numbers in the list

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

  2. The sum of the list of numbers

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

  3. Substring occurrence check

     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 } .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. Filtering a list of numbers

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

  7. Receiving and parsing XML from a web service

     require 'open-uri' require 'hpricot' results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala")) 
    In this example, open-uri and hpricot or equivalent libraries are required (you can use the built-in). This is not too much code, but Scala clearly wins here.

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

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

  9. Parallel processing

     require 'parallel' Parallel.map(lots_of_data) do |chunk| heavy_computation(chunk) end 
    Unlike Scala, multi-core support is not built in. This example requires a parallel or similar gem.

  10. Sieve eratosthene

    One-liner on Scala is very abstruse, but completely unreadable. A simple implementation requiring more than one line in 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 
    This example is with StackOverflow .

Original post: "10 Ruby One Liners to Impress Your Friends"
Posted by: Antonio Cangiano


Clojure


I saw an interesting post today titled “ 10 Scala to help you impress your friends, ” and then someone posted a blog post on another blog titled “ 10 CoffeeScript to build your friends ”. These two posts show small puzzles (most of them have trivial solutions in modern programming languages), each of which is made in about 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 the list

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

  2. The sum of the list of numbers

     (reduce + (range 1 1001)) 

  3. Substring occurrence check

    I think it's right 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 
    As the commentators suggested, this problem can be solved without using regular expressions by using Clojure sets.
     (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. Reading file

     (def file-text (slurp "data.txt")) ;    (def file-lines (clojure.contrib.io/read-lines "data.txt")) ;    
    Clojure Contrib will be considered obsolete in future Clojure releases, clojure.contrib.io/read-lines can be written as (line-seq (clojure.java.io/reader (clojure.java.io/file “data.txt”))) in Clojure 1.3 and older. Thanks Aaron for pointing this out.

  5. Happy Birthday

     (doseq [l (map #(str "Happy Birthday " (if (= % 2) "dear Rich" "to You")) (range 4))] (println l)) 
    Alternative version:
     (dotimes [n 4] (println "Happy Birthday " (if (= n 2) "dear Rich" "to You"))) 

  6. Filtering a list of numbers

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

  7. Getting and parsing XML from a web service

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

  8. Search for the minimum and maximum in the list

     (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. Parallel processing

     ;; ,  process-line -     ,    (pmap process-line lines) ;    "p"  map 

  10. Sieve of Eratosthenes

    I am not good enough (in terms of performance and beauty) for the one-line solution of the “Sieve of Eratosthenes”. I recommend checking out the work of Christoph Granda on this topic called “Everyone loves Sieve Eratosthenes” to solve this problem.

  11. FizzBuzz Solution

     (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 Scala / Ruby / Clojure / CoffeeScript one-liners, I thought it would be interesting to do the same in Python.

Without much noise ... let's go. Note that variable declarations and imports in separate lines as needed. Also, each line is written to display the result on standard output for a quick check.

This post is probably one of the fastest that I wrote.
  1. Doubling all numbers in the list

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

  2. The sum of the list of numbers

     print sum(range(1,1001)) 

  3. Substring occurrence check

     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. Reading 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. Filtering a list of numbers

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

  7. Receiving 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 the 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 to impress your friends"
Posted by: Dhananjay Nene


C #


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

  2. The sum of the list of numbers

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

  3. Substring occurrence check

     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. Reading 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. Filtering a list of numbers

     var passed = new List<int>(); var failed = new List<int>(); (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<int>)passed); Print("Filter list of numbers <=60", (IEnumerable<int>)failed); 

  7. Receiving 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 the 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


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

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

  2. The sum of the list of numbers

     foldl (+) 0 [1..1000] --   sum [1..1000] 

  3. Substring occurrence check

     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. Reading 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. Filtering a list of numbers

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

  7. Receiving and parsing XML from a web service

    This example requires the curl and xml packages. See the 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 the 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

    This example requires the parallel package.
     import Control.Parallel import Control.Parallel.Strategies parMap rseq (*2) [1..100] 

  10. Generation of prime numbers

     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 yes begin holivary! )

Source: https://habr.com/ru/post/120665/


All Articles