繁体   English   中英

F#:使用List.map调用seq方法中的方法

[英]F#: Using List.map to call methods in a seq of methods

基本上我有一个方法列表,我想迭代,调用方法,并返回方法返回值列表。 我可以使用Linq语法。

member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
    methodList.Select((fun (item:String -> Int32) -> item(input))).ToList()

但是,我不能得到地图太工作,我猜测是我缺乏F#语法知识。

member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
    methodList |> List.map (fun (item) -> item(input))

不应该意味着map方法将接受seq <(String - > Int32)>,迭代,调用每个方法,并返回Int32列表?

因为methodList是F#中的序列,所以不能将其视为列表(它是其子类型之一)。 因此,请确保对序列使用高阶函数并将结果转换为列表:

member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
    methodList |> Seq.map (fun (item) -> item(input)) |> Seq.toList

List.map需要列表<'a>但您明确声明methodList是seq <..>。 可能的解决方案:

// 1. type of methods will be inferred as list
let takeIn (methods, input : string) : int list = 
    methods 
    |> List.map (fun f -> f input) 
// 2. explicitly convert result to list 
let takeIn (methods, input : string) : int list = 
    methods 
    |> Seq.map (fun f -> f input) 
    |> Seq.toList 
// 3. same as 2 but using list sequence expressions
let takeIn (methods, input : string) : int list = [for f in methods do yield f input] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM