Skip to content

Instantly share code, notes, and snippets.

@ilkerde
Created February 2, 2012 10:45
Show Gist options
  • Save ilkerde/1722848 to your computer and use it in GitHub Desktop.
Save ilkerde/1722848 to your computer and use it in GitHub Desktop.
FSharp Flexibility
// A case for FSharp: Flexibility Applied
// --------------------------------------
//
// Consider a Where expression in C#
// nums.Where(x => 0 <= x); //yoda-esque
//
// Let's see F# doing this.
let nums = [-2 .. 2];;
// Take 1: one to one translation of c#
nums |> Seq.filter (fun x -> 0 <= x);;
// Take 2: eliminate yoda (still possible in c#)
nums |> Seq.filter (fun x -> x >= 0);;
// Take 3: eliminate lamda with <= function and partial application
nums |> Seq.filter ((<=) 0);;
// Take 4: use language-orientation for expressiveness
let removeAll = Seq.filter;;
let lessThan = (<=);;
nums |> removeAll (lessThan 0);;
@forki
Copy link

forki commented Feb 2, 2012

The last one is not really right.

  • lessThan 0 4 returns true.
  • removeAll removes all elements where the predicate is false (??)

So let's fix this:

let removeAll f = Seq.filter (f >> not)
let lessThan = (>)

let nums = [-2 .. 2]

nums |> removeAll (lessThan 0) |> printfn "%A"

@ilkerde
Copy link
Author

ilkerde commented Feb 2, 2012

You're right. I quickly hacked this together before leaving to lunch. Should've better not done this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment