Will.Whim

A weblog by Will Fitzgerald

Category Archives: F#

F# One liners to impress your friends

In the spirit of 10 Scale One Liners to impress your friends, here are some F# one liners:

  1. Multiply each item in a list by 2.
    This is simple to do; F# has map: [1 .. 4] |> Seq.map (fun x -> x * 2);;
    val it : seq = seq [1; 4; 9; 16]
  2. Sum a list of numbers.
    This is simple to do, too F# has sum:[1 .. 4] |> Seq.sum;;
    val it : int = 10
  3. Verify if any item in a sequence exists in a string
    This is simple to do; F# has find:>["f#"; "scala"] |> Seq.find(fun w -> "this tweet contains f#".Contains(w));;
    val it : string = "f#"
  4. Read in a file (boooring!)F# has all the libraries of .NET behind it. It’s easy to treat read lines as a sequence
    File.ReadLines(@"file.txt") |> Seq.map(fun l -> l.Length) |> Seq.sum;;
    val it : int = 198183
  5. Happy birthday to you!Also boring… but here it is:
    [1 .. 4] |> Seq.map (fun i -> "Happy Birthday " + (if i = 3 then "dear NAME" else "to you")) |> Seq.iter Console.WriteLine;;
  6. Filter (actually, partition) lists of numbersUsing the built in partition function, we can easily partition lists:
    [49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;
    val it : int list * int list = ([76; 82; 88; 90], [49; 58])
  7. Fetch and parse XML
    Again, the .NET libraries come in handy. Unfortunately, this isn’t exactly a one-liner in F#. But Don Syme shows how to do this both synchronously and asynchronously.
  8. Find the minimum and maximum in a list.
    F# has min and max built in:
    > [49; 58; 76; 82; 88; 90] |> Seq.min;;
    val it : int = 49
    > [49; 58; 76; 82; 88; 90] |> Seq.max;;
    val it : int = 90
  9. Parallel processing
    This example comes from J Rocha. Assume we have an ‘isprime’ method (which, of course, will be somewhat expensive to calculate), and we want to get a count of prime numbers grouped by their final digit, from 1 to 50,000. PSeq processes sequences in parallel (so filtering and grouping and mapping are happening in parallel in this example):
    > [|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;;
    val it : (int * int) list =
    [(1, 1275); (2, 1); (3, 1290); (5, 1); (7, 1288); (9, 1279)]

Is this impressive enough?