具有F#函数类型的扩展方法 [英] Extension method with F# function type

查看:50
本文介绍了具有F#函数类型的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关类型扩展的MSDN文档指出:在F#3.1之前,F#编译器不支持使用具有通用类型变量,数组类型,元组类型或F#函数类型作为C#样式的扩展方法.此"参数."( http://msdn.microsoft.com/en-us/library/dd233211.aspx )如何在F#函数类型上使用类型扩展?在什么情况下,此功能有用?

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?

推荐答案

以下是您的操作方法:

[<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了,在F#中根本不是习惯用法.

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

这篇关于具有F#函数类型的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆