简体   繁体   中英

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.

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.

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?

Because methodList is a sequence in F#, you can't treat it as a list (which is one of its subtypes). 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<..>. 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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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