Extension Method with Functional Type F #

An MSDN document in type extensions states that "prior to F # 3.1, the F # compiler did not support the use of C # class extension methods with a variable of type general type, array type, tuple type, or F # function type like" this "". ( http://msdn.microsoft.com/en-us/library/dd233211.aspx ) How can there be a type extension used for an F # function type? In what situations can such a function be useful?

+4
source share
2 answers

Here's 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

" ?", , , , , , - . JavaScript-ey, F #.

+4

. F # |>. , :

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
+1

Source: https://habr.com/ru/post/1538057/


All Articles