HOWTO写一个函数以在F#可变数量的参数 [英] Howto write a function taking variable number of arguments in F#

查看:122
本文介绍了HOWTO写一个函数以在F#可变数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在C#中的函数,我想将它移植(其中一些其他的东西)到F#的,只是为了做它的缘故。不幸的是,我只打了其中似乎有没有办法来表达这种在F#的情况下:取本C#功能



 公开静态T最小< T>(PARAMS T [] p),其中T:IComparable的
{$ b $(b T)M1 = p [0];

的foreach(P中Ťⅴ)
{
M1 =(m1.CompareTo(V)小于0)? M1:伏;
}

返回M1;
}



我还以为这将是很容易的,但我不明白我怎么会指定F#变量参数列表。我曾尝试这样的:



<预类=郎毫升prettyprint-覆盖> 让REC分钟L =
匹配l对于
| [] - > 0 //应该抛出异常这里
| [V] - GT; V $ B $ C | (H :: T) - >分H(闽T)



但调用从C#需要一个微软。 FSharp.Collections.List 。是否有可能得到它期望 PARAMS T [] ,如果是这样,怎么样?


解决方案

一个参数数组是简单地用一个属性的数组,乔恩说。参数前添加属性。





<预类=郎毫升prettyprint-覆盖> 让测试([ <&的ParamArray GT] ARR:一个数组)=
如果arr.Length = 0,则invalid_arg改编
// ...

您不需要指定类型:



<预类=郎毫升prettyprint-覆盖 > 让测试([LT;的ParamArray>] ARR)= ... //让类型推断做它的事

但是...模式匹配不上的数组类型的工作。你可以写一个积极的方式提供帮助。基本上,你必须决定什么更重要:F#的代码或C#代码。为您设计高阶功能,使用元组同样的权衡将适用,使用歧视工会等C#不能表达大多数事情,和F#目前不支持一些糖C#的小位在(表达式树的写作编译器,例如)。


I've got a function in C#, and I'd like to port it (among some other stuff) over to F#, just for the sake of doing it. Unfortunately, I just hit a case for which there seems to be no way to express this in F#: Take this C# function

public static T Min<T>(params T[] p) where T : IComparable
{
    T m1 = p[0];

    foreach (T v in p)
    {
        m1 = (m1.CompareTo(v) < 0) ? m1 : v;
    }

    return m1;
}

I'd thought this would be pretty easy, but I don't understand how I would specify a variable argument list in F#. I have tried this:

let rec Min l =
    match l with
    | [] -> 0 // should throw exception here
    | [v] -> v
    | (h::t) -> min h (Min t)

but calling that from C# expects a Microsoft.FSharp.Collections.List. Is it possible to get it expect a params T[], and if so, how?

解决方案

A params array is simply an array with an attribute, as Jon notes. Add the attribute before the parameter.

let test ([<ParamArray>] arr : 'a array) = 
    if arr.Length = 0 then invalid_arg "arr"
    // ....

You don't need to specify the type:

let test ([<ParamArray>] arr) = ... // lets type inference do its thing

But... pattern matching doesn't work on the array type. You could write an active pattern to help. Basically, you have to decide what's more important: the F# code or the C# code. The same tradeoff will apply as you design higher order functions, use tuples, use discriminated unions, etc. C# can't express most things, and F# doesn't currently support some of the little bits of sugar C# has (Expression Tree writing in the compiler, for example).

这篇关于HOWTO写一个函数以在F#可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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