Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method with F# function type

The MSDN doc on Type Extensions states that "Before F# 3.1, the F# compiler didn't support the use of C#-style extension methods with a generic type variable, array type, tuple type, or an F# function type as the “this” parameter." (http://msdn.microsoft.com/en-us/library/dd233211.aspx) How can be a Type Extension used on F# function type? In what situations would such a feature be useful?

like image 860
wlabaj Avatar asked Apr 25 '14 11:04

wlabaj


People also ask

What is extension method with example?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method in OOP?

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.

What is extension method in Python?

The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.


2 Answers

Here is how you can do it:

[<Extension>]
type FunctionExtension() =
    [<Extension>]
    static member inline Twice(f: 'a -> 'a, x: 'a) = f (f x)

// Example use
let increment x = x + 1
let y = increment.Twice 5  // val y : int = 7

Now for "In what situations would such a feature be useful?", I honestly don't know and I think it's probably a bad idea to ever do this. Calling methods on a function feels way too JavaScript-ey, not idiomatic at all in F#.

like image 78
Tarmil Avatar answered Nov 15 '22 08:11

Tarmil


You may simulate the . notation for extension methods with F#'s |> operator. It's a little clumsier, given the need for brackets:

let extension f x =
    let a = f x
    a * 2

let f x = x*x

> f 2;;
val it : int = 4
> (f |> extension) 2;;
val it : int = 8
> let c = extension f 2;;  // Same as above
val c : int = 8
like image 34
Mau Avatar answered Nov 15 '22 06:11

Mau