2013-10-06 34 views
1

這裏是我的代碼:爲什麼Console.WriteLine無法確定我的類型?在F#

open System 

let places = [ ("Grandchester", 552); 
       ("Cambridge", 117900); 
       ("Prague", 1188126); ] 

let statusByPopulation = function 
          | n when n > 1000000 -> "City" 
          | n when n > 50000 -> "Town" 
          | _     -> "Village" 

System.Console.WriteLine (places |> List.map (fun (_, population) -> statusByPopulation population)) 

let print x = 
    Console.WriteLine (List.map (fun (_, population) -> statusByPopulation population) x) // what I'm trying to do 

let something (x:(string * int) list) = 
    List.map (fun (_, population) -> statusByPopulation population) x; // checking what kinf of type it returns 

let print: (string * int) list -> unit = 
    Console.WriteLine << List.map (fun (_, population) -> statusByPopulation population) // what I'm not allowed to do 

System.Console.ReadKey() |> ignore 

我想熟悉的函數組合運營商合作的方式,但由於某種原因,F#無法找到最佳的重載函數...

在我明確狀態的參數的例子,它設置類型爲val print : x:('a * int) list -> unit,所以我明確地設置型與複合算<<功能,希望我能得到正確的結果......我沒有。 ..

然後我做了功能something爲參數顯式聲明的類型,只是爲了看看它會返回什麼...它返回這個:val something : x:(string * int) list -> string list

所以它最肯定返回一個類型...一個字符串列表,我知道控制檯。 WriteLine能夠打印...那麼爲什麼它告訴我它不能確定過載?

+0

類型推理工作從左到右;使用流水線('|>')來調用'Console.WriteLine'。 – ildjarn

+0

我不想使用流水線,我要保存一個參數... '˚F<< G = F(G(X))= G(X)|> F' –

+3

我不知道你是什​​麼意思。有什麼問題'x |> List.map(fun(_,population) - > statusByPopulation population)|> Console.WriteLine'? (或者更簡潔地說,'X |> List.map(SND >> statusByPopulation)|> Console.WriteLine'?) – ildjarn

回答

4

F#中的類型推斷從左到右工作 - 這意味着編譯器使用程序中早些時候提供的信息來確定稍後在程序中的表達式類型(這只是一個簡單的簡化,但它是一般的理念)。

在你的代碼

所以,當你寫:

Console.WriteLine << List.map (fun (_, population) -> statusByPopulation population) 

..編譯器不傳播有關函數的輸入通過List.map回調到WriteLine呼叫類型的信息。這也解釋了爲什麼前向鏈和組合在F#中通常更有用。以下作品:

List.map (fun (_, population) -> statusByPopulation population) >> Console.WriteLine 

爲了讓您的原代碼的工作,你可以提供的是需要確定正確的WriteLine超載是一個以object信息的一些很小的量。如果你告訴編譯器它需要列出一些東西,那麼它可以選擇正確的過載:

(Console.WriteLine:list<_> -> unit) << List.map (fun (_, population) -> 
    statusByPopulation population) 
+0

謝謝,這正是我需要的答案 –

+3

而這基本上是@ildjarn在他的評論中所說的以上。 –

相關問題