Compose功能下面.如果是f并且g是返回值的一元函数,则Compose(f,g)返回一个函数,该函数在被调用时x执行等价于f(g(x)).
static Func<X, Z> Compose<Z, Y, X>(Func<Y, Z> f,Func<X, Y> g)
{ return x => f(g(x)); }
Run Code Online (Sandbox Code Playgroud)
这里有几个简单的Func值可以组成:
Func<int, bool> is_zero = x => { return x == 0; };
Func<int, int> mod_by_2 = x => { return x % 2; };
Run Code Online (Sandbox Code Playgroud)
这有效:
Console.WriteLine(Compose(is_zero, mod_by_2)(4));
Run Code Online (Sandbox Code Playgroud)
但是,如果我改为使用这些等效的静态方法:
static bool IsZero(int n) { return n == 0; }
static int ModBy2(int n) { return n % 2; }
Run Code Online (Sandbox Code Playgroud)
同样的例子不适用于那些.即这会产生编译时错误: …
给出一个简单的元组序列,以及使用F#PowerPack的PSeq的并行序列:
let a = Seq.singleton (1,"a") --> val a: seq<int * string>
let b = a |> PSeq.map id --> val b: pseq<int * string>
Run Code Online (Sandbox Code Playgroud)
现在我想从他们创建一个.Net BCL字典:
let bd = b.ToDictionary(fst, snd, HashIdentity.Structural)
let ad = a.ToDictionary(fst, snd, HashIdentity.Structural)
let ad2 = a.ToDictionary(fst, snd)
let ad3 = a.ToDictionary((fun (x,y) -> x), (fun (x,y) -> y), HashIdentity.Structural)
Run Code Online (Sandbox Code Playgroud)
虽然let bd有效let ad但无法编译,因为它无法推断类型并正确转换为BCL的Func.有趣的是,如果我省略第三个参数let ad2,或者如果我写出来fst并snd手动内联,它就可以正常工作let ad3.
该表达式应该具有类型Func <(int*string),'a>但这里有类型'b*'c - >'b
let ad …F#
let s = "bugs 42 bunny"
s.Count(fun c -> Char.IsLetter(c))
s.Where(fun c -> Char.IsLetter(c)).ToArray()
s.Where(Char.IsLetter).ToArray()
s.Count(Char.IsLetter) // error
Run Code Online (Sandbox Code Playgroud)
为什么只有最后一行无法编译:
错误FS0002:此函数需要太多参数,或者在不期望函数的上下文中使用