gpt4 book ai didi

F# 等价于 Enumerable.OfType<'a>

转载 作者:行者123 更新时间:2023-12-03 20:26:30 26 4
gpt4 key购买 nike

...或者,我如何通过它们实现的接口(interface)过滤一系列类?

假设我有一个继承自 Foo 的对象序列,即 seq<#Foo>。 .换句话说,我的序列将包含 Foo 的四个不同子类中的一个或多个。

每个子类实现不同的独立接口(interface),与其他子类实现的接口(interface)不共享任何内容。

现在我需要将此序列过滤为仅实现特定接口(interface)的项目。

C# 版本很简单:

    void MergeFoosIntoList<T>(IEnumerable<Foo> allFoos, IList<T> dest) 
where T : class
{
foreach (var foo in allFoos)
{
var castFoo = foo as T;
if (castFoo != null)
{
dest.Add(castFoo);
}
}
}

我可以使用 F# 中的 LINQ:
    let mergeFoosIntoList (foos:seq<#Foo>) (dest:IList<'a>) =
System.Linq.Enumerable.OfType<'a>(foos)
|> Seq.iter dest.Add

但是,我觉得应该有一种更惯用的方式来完成它。我以为这会奏效...
    let mergeFoosIntoList (foos:seq<#Foo>) (dest:IList<'a>) =
foos
|> Seq.choose (function | :? 'a as x -> Some(x) | _ -> None)
|> Seq.iter dest.Add

然而,编译器提示 :? 'a - 告诉我:

This runtime coercion or type test from type 'b to 'a involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed.



我不知道要添加什么进一步的类型注释。接口(interface) 'a之间没有关系和 #Foo除了 Foo 的一个或多个子类实现该接口(interface)。此外,可以作为 'a 传入的不同接口(interface)之间没有关系。除了它们都是由 Foo 的子类实现的。

一旦你们中的一个好心人指出我一直遗漏的明显事情,我热切期待自己的脑袋。

最佳答案

你可以这样做:

let foos = candidates |> Seq.filter (fun x -> x :? Foo) |> Seq.cast<Foo>

关于F# 等价于 Enumerable.OfType<'a>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com