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*)
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
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(_))
val fileText = io.Source.fromFile("data.txt").mkString val fileLines = io.Source.fromFile("data.txt").getLines.toList
map
and foreach
. (1 to 4).map { i => "Happy Birthday " + (if (i == 3) "dear NAME" else "to You") }.foreach { println }
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 )
val results = XML.load("http://search.twitter.com/search.atom?&q=scala")
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
foreach
, map
, filter
, etc ... Here is a video from Alexander Prokopets about parallel collections on Scala Days 2010. val result = dataList.par.map(line => processItem(line))
(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 .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]
map
and reduce
functions: [1..1000].reduce (t, s) -> t + s
(reduce == reduceLeft, reduceRight is also available)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. 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. [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]
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) request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body
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
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
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]
map
: [1 .. 4] |> Seq.map (fun x -> x * x);;
sum
: [1 .. 4] |> Seq.sum;;
find
: ["f#"; "scala"] |> Seq.find(fun w -> "this tweet contains f#".Contains(w));;
File.ReadLines(@"file.txt") |> Seq.map(fun l -> l.Length) |> Seq.sum;;
[1 .. 4] |> Seq.map (fun i -> "Happy Birthday " + (if i = 3 then "dear NAME" else "to you")) |> Seq.iter Console.WriteLine;;
partition
function, we can easily split the list: [49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;
[49; 58; 76; 82; 88; 90] |> Seq.min;; [49; 58; 76; 82; 88; 90] |> Seq.max;;
[|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;;
(1..10).map { |n| n * 2 }
(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(:+)
words = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." words.any? { |word| tweet.include?(word) }
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/)
4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }
[49, 58, 76, 82, 88, 90].partition { |n| n > 60 }
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. [14, 35, -7, 46, 98].min [14, 35, -7, 46, 98].max
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. 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 . (map #(* % 2) (range 1 11))
(reduce + (range 1 1001))
(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
(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. (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")))
(partition-by #(> % 60) [49 58 76 82 88 90])
(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
(map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 3)) "Fizz" (zero? (mod % 5)) "Buzz" :else %) (range 1 101))
print map(lambda x: x * 2, range(1,11))
print sum(range(1,1001))
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)
print open("ten_one_liners.py").readlines()
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))
print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
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")
print min([14, 35, -7, 46, 98]) print max([14, 35, -7, 46, 98])
import multiprocessing import math print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
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))))
Print("Multiple each item in a list by 2", Enumerable.Range(1, 10).Select(i => i * 2));
Print("Sum a list of numbers", Enumerable.Range(1, 1000).Sum());
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));
Print("Read in a File", File.ReadAllBytes("oneliners.exe").Length);
Print("Happy Birthday", Enumerable.Range(1, 4).Select((i) => string.Format("Happy Birthday {0} ", i == 3 ? "dear NAME" : "to You")));
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);
Print("Fetch and Parse an XML web service", XDocument.Load("http://search.twitter.com/search.atom?&q=scala"));
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 }));
Print("Parallel Processing", Enumerable.Range(1, 10).AsParallel().Select((i)=>i*2).AsEnumerable());
Print("Fizzbuzz", Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":"")));
map (*2) [1..10]
foldl (+) 0 [1..1000] -- sum [1..1000]
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
fileText <- readFile "data.txt" let fileLines = lines fileText -- let fileLines = fmap lines $ readFile "data.txt"
mapM_ putStrLn ["Happy Birthday " ++ (if x == 3 then "dear NAME" else "to You") | x <- [1..4]]
let (passed, failed) = partition (>60) [49, 58, 76, 82, 88, 90]
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" []
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
package. import Control.Parallel import Control.Parallel.Strategies parMap rseq (*2) [1..100]
let pgen (p:xs) = p : pgen [x|x <- xs, x `mod` p > 0] take 40 (pgen [2..])
Source: https://habr.com/ru/post/120665/
All Articles