20 people like it.

Currying

Currying is about fixing arguments of functions from left to right. It's useful to configurate code and embed parameters that usually serve to define the context of a function execution (i.e. a database connection object). Symbolic functions can be used to reorder arguments if needed.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
// Simple add function
let add x y = x + y

// We fix the first argument to derive the increment function
let inc = add 1

printfn "%d = %d" (inc 5) (add 1 5)

//Can we do the same with subtract?
let sub x y = x - y

let decw = sub 1 // WRONG: this is 1 - y and not x - 1!

printfn "%d = %d" (decw 5) (sub 1 5)

// Let's define a function that reorder arguments
let invert2 f y x = f x y

let dec = invert2 sub 1

printfn "%d = %d" (dec 5) (sub 5 1)
val add : x:int -> y:int -> int

Full name: Script.add
val x : int
val y : int
val inc : (int -> int)

Full name: Script.inc
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val sub : x:int -> y:int -> int

Full name: Script.sub
val decw : (int -> int)

Full name: Script.decw
val invert2 : f:('a -> 'b -> 'c) -> y:'b -> x:'a -> 'c

Full name: Script.invert2
val f : ('a -> 'b -> 'c)
val y : 'b
val x : 'a
val dec : (int -> int)

Full name: Script.dec
Raw view Test code New version

More information

Link:http://fssnip.net/I
Posted:14 years ago
Author:Antonio Cisternino
Tags: currying