2017-04-11 46 views
1

我注意到管道通向/來自某些.NET方法的困難。玩具例如與#net對象管道連接的F#

let foo = System.String [| 'a'; 'b'; 'c' |] // works 
let foo = [| 'a'; 'b'; 'c' |] |> System.String // fails 
// error FS0802: Invalid use of a type name and/or object constructor. 
let foo = System.String <| [| 'a'; 'b'; 'c' |] // fails the same way 
let foo = [| 'a'; 'b'; 'c' |] |> new System.String // Fails 
// error FS0010: Incomplete structured construct at or before this point in expression 

基本上,我想弄清楚的時候,你可以用.NET對象,當不結合管道。如果有參考,我很樂意獲得鏈接!

+6

你的例子(除了最後一個,這是非法的語法)在F#4中工作。他們[增加了支持將構造函數視爲函數](https://blogs.msdn.microsoft.com/fsharpteam/2014/11/ 12 /宣佈-A-預覽-F-4-0的 - 和 - 的視覺-F-工具 - 在-VS-2015 /)。您使用的是哪個版本的F#? –

+0

我正在運行Microsoft(R)F#交互版本11.0.60610.1 版權所有(c)Microsoft Corporation。版權所有。 – user1443098

+1

是的,這是一個非常舊的版本,F#4有交互式版本14,所以我猜你正在使用F#3(可能甚至是老一些)......無論如何,無論你升級到至少Visual Studio 2015還是你有如鏈接的博客文章中所述,使用'|> fun chars - > System.String chars' lambdas。 –

回答

2

至於你用繩子具有掛斷,下面的鏈接將顯示用於治療構造的功能支持,加入到F#4.0

https://fslang.uservoice.com/forums/245727-f-language/suggestions/5663317-allow-to-use-class-constructors-as-functions

另一種常見的情況,使管道從尷尬.NET庫是它們公開爲tupled(而不是curried)函數參數,這些參數可以使部分應用函數管道更加痛苦。圍繞這些笨重的.NET函數創建curry包裝通常是一個很好的解決方法。

+0

創建curried包裝的一個很好的例子是我經常在自己的代碼中寫入的函數:'let strJoin(between:string)(parts:#seq )= System.String.Join(between,parts)'。 (類型註釋是必須的,以便編譯器可以找出'System.String.Join'的唯一重載)。然後,我可以編寫類似'listOfInts |> List.map intToHexStr |> strJoin「,」|> sprintf「[%s]」的代碼,結果字符串看起來像是[0x1,0x2,0xdeadbeef]。簡單,易讀,可移植,而'System.String.Join'不可移植。 – rmunn