dha*_*ech 3 .net extension-methods f# func
正如在这个问题中提到的,期望a的方法Func
不接受F#函数值.
重载一个方法以便接受F#函数值的好方法是什么?
我知道这不是你要求的,而是直接尝试用C#编写的代码来支持F#(因为我得到你想要的印象),提供一个小的适配器模块会更加惯用使F#的功能性组合更容易.
有很多这样的例子,比如FSharp.Reactive,它提供了一些函数,可以更容易地使用F#中的Reactive Extensions.
例如,如果您想从F#访问Enumerable.All,您可以编写一个小适配器函数,例如
let all f (s : 'a seq) = s.All (fun x -> f x)
Run Code Online (Sandbox Code Playgroud)
你可以这样使用: -
seqA |> all abc
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下All
,您可以使用内置的F#函数:
seqA |> Seq.forall abc
Run Code Online (Sandbox Code Playgroud)
以下是将 F# 函数值传递给 的示例IEnumerable.All
:
open System.Linq
open IEnumerableAllFSharpFunc
let seqA = seq { 1..10 }
let abc n = n > 0
seqA.All abc |> printfn "%A"
Run Code Online (Sandbox Code Playgroud)
给出这个扩展方法IEnumerable.All
:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.FSharp.Core;
namespace IEnumerableAllFSharpFunc
{
public static class Utils
{
public static bool All<T>(this IEnumerable<T> seq, FSharpFunc<T, bool> pred)
{
var converter = FSharpFunc<T, bool>.ToConverter(pred);
Func<T, bool> func = (elt) => converter(elt);
return seq.All(func);
}
}
}
Run Code Online (Sandbox Code Playgroud)
欢迎更优雅的方法。:-)