Monday, 9 September 2013

Ten F# one-liners to impress your friends

These ten one-liners are trending in other languages so here is an F# translation:

Multiply each item in a list by two
[for n in 1..10 -> 2*n]

Sum a list of numbers
Seq.sum [1..1000]

Verify if word exists as a substring in a string
Seq.exists tweet.Contains wordList

Read a file as a single string or line-by-line
System.IO.File.ReadAllText "data.txt"
System.IO.File.ReadLines "data.txt"

Happy birthday to you
for i in 1..4 do printfn "Happy Birthday %s" (if i=3 then "dear NAME" else "to You")

Filter list of numbers
let failed, passed = List.partition ((>) 60) [49; 58; 76; 82; 88; 90]

Load XML
#r "System.Xml.Linq"; System.Xml.Linq.XDocument.Load "data.xml"

Find min/max of list of numbers
Seq.min [14; 35; -7; 46; 98]
Seq.max [14; 35; -7; 46; 98]

Parallel processing
Array.Parallel.map ((*) 2) [|1..100|]

Primes
Seq.filter (fun i -> Seq.forall (fun j -> i%j<>0) [2..i-1]) [2..50]

1 comment:

Brian said...

Primes
Seq.filter (fun i -> Seq.forall (fun j -> i%j<>0) [2..(float>>sqrt>>int)i]) [2..50]