Extension method with F# function type

时间秒杀一切 提交于 2019-12-12 11:14:26

问题


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?


回答1:


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#.




回答2:


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


来源:https://stackoverflow.com/questions/23292379/extension-method-with-f-function-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!