user1443098
user1443098

Reputation: 7645

F# pure functions and currying

If I have a function:

let f (myClass : MyClass) x = 
    // do something using the instance of myClass and x

and I curry f like this:

let myClass = new MyClass()
let g = f myClass

so I can just call

let something = f 42

is g a pure function? Or does it's captured reference to the instance of MyClass make it impure?

Upvotes: 2

Views: 238

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

It depends on which functions (or methods) the function calls and whether those functions (or methods) are pure or not. Captured object is completely irrelevant.

A function is considered "pure" if it satisfies two conditions: (1) it always returns same result given same arguments and (2) it doesn't produce any side effects (which include things like input/output or mutating data). Whether or not the function has any data captured in a closure is largely irrelevant to the concept of purity.

For example, the following function would be pure, even though it captures an object in a closure:

let f (c: MyClass) x = if c = null then x else x+1
let g = f (MyClass ())

But the following functions are impure, even though it doesn't capture any data:

let g1 x = printfn "%d" x
let g2 x = System.DateTime.Now.Minute + x

In this example, g1 is impure, because it produces a side effect in the form of output to the console; and g2 is impure, because it returns a different result every time it's called.

The original idea behind this definition of purity (also referred to as "referential transparency") was that an invocation of a pure function within a program can be replaced with its result without alerting the meaning of the program. This is in turn useful for all kinds of optimizations and proofs.

For example, any invocation of g (as defined above) can be safely replaced with its result (e.g. replace g 5 with 6), but invocations of g1 cannot, because that will alter the program's console output.

Upvotes: 2

Related Questions