[英]F#: Using List.map to call methods in a seq of methods
Basically I have a list of methods that I want to iterate through, call the methods, and return the list of method return values. 基本上我有一个方法列表,我想迭代,调用方法,并返回方法返回值列表。 I can get it working with Linq syntax. 我可以使用Linq语法。
member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
methodList.Select((fun (item:String -> Int32) -> item(input))).ToList()
However I can't get map too work which I'm guessing is my lack of F# syntax knowledge. 但是,我不能得到地图太工作,我猜测是我缺乏F#语法知识。
member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
methodList |> List.map (fun (item) -> item(input))
Shouldn't that imply that the map method will take in a seq<(String -> Int32)>, iterate through, call each method, and return a list of Int32? 不应该意味着map方法将接受seq <(String - > Int32)>,迭代,调用每个方法,并返回Int32列表?
Because methodList
is a sequence in F#, you can't treat it as a list (which is one of its subtypes). 因为methodList
是F#中的序列,所以不能将其视为列表(它是其子类型之一)。 So make sure that you use high-order functions for the sequence and convert the result to a list: 因此,请确保对序列使用高阶函数并将结果转换为列表:
member public x.TakeIn(methodList : seq<(String -> Int32)>, input:String) =
methodList |> Seq.map (fun (item) -> item(input)) |> Seq.toList
List.map requires list<'a> but you explicitly declare that methodList is seq<..>. List.map需要列表<'a>但您明确声明methodList是seq <..>。 Possible solutions: 可能的解决方案:
// 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.