Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing anonymous function construct

Tags:

f#

I'm reading through an F# tutorial, and ran into an example of syntax that I don't understand. The link to the page I'm reading is at the bottom. Here's the example from that page:

let rec quicksort2 = function
   | [] -> []                         
   | first::rest -> 
        let smaller,larger = List.partition ((>=) first) rest 
        List.concat [quicksort2 smaller; [first]; quicksort2 larger]

// test code        
printfn "%A" (quicksort2 [1;5;23;18;9;1;3])

The part I don't understand is this: ((>=) first). What exactly is this? For contrast, this is an example from the MSDN documentation for List.partition:

let list1 = [ 1 .. 10 ]
let listEven, listOdd = List.partition (fun elem -> elem % 2 = 0) list1
printfn "Evens: %A\nOdds: %A" listEven listOdd

The first parameter (is this the right terminology?) to List.partition is obviously an anonymous function. I rewrote the line in question as this:

let smaller,larger = List.partition (fun e -> first >= e) rest 

and it works the same as the example above. I just don't understand how this construct accomplishes the same thing: ((>=) first)

http://fsharpforfunandprofit.com/posts/fvsc-quicksort/

like image 928
Tim Coker Avatar asked Feb 06 '23 17:02

Tim Coker


1 Answers

That's roughly the same thing as infix notation vs prefix notation
Operator are functions too and follow the same rule (ie. they can be partially applied)

So here (>=) first is the operator >= with first already applied as "first" operand, and gives back a function waiting for the second operand of the operator as you noticed when rewriting that line.

like image 189
Sehnsucht Avatar answered Feb 08 '23 05:02

Sehnsucht