typestar

Currying in F#

Every function takes one argument; partial application is free.

// Every function takes one argument; more arguments mean curry.
let feed syrupLiters hive =
    sprintf "%s gets %.1f L of syrup" hive syrupLiters

// Partial application bakes in the first argument.
let autumnFeed = feed 2.5
printfn "%s" (autumnFeed "Willow")
printfn "%s" (autumnFeed "Bramble")

// Type annotations are allowed but inference usually wins.
let addSuper (frames: int) hive =
    sprintf "%s grows to %d frames" hive (frames + 10)
printfn "%s" (addSuper 8 "Clover")

How it works

  1. feed syrupLiters hive is really two nested functions.
  2. feed 2.5 bakes in the first argument and returns the rest.
  3. Annotations like (frames: int) steer inference when needed.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
474
Tokens
71
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 1 of 3 in Functions, step 4 of 27 in Language basics.

← Previous Next →

Currying in other languages