2011-11-10 24 views
2

基本上我有一個我想要遍歷的方法列表,調用方法並返回方法返回值列表。我可以使用Linq語法來處理它。F#:使用List.map調用方法中的方法

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)) 

難道不應該暗示地圖方法將在一個序列<(字符串 - >的Int32)>,遍歷,調用每個方法,並返回的Int32的名單?

+0

觀察到,如果您在C#版本中刪除了「ToList」,則會出現同樣的問題。 – Benjol

回答

5

因爲methodList是F#中的一個序列,所以不能把它當作一個列表(它是它的一個子類型)。因此,請確保您使用高階函數序列,並將結果轉換到一個列表:

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

List.map要求列表<「一個>但你明確聲明methodList時是序列<...>。可能的解決方案:

// 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]