2017-08-08 133 views
4

在這樣的問題:In F# how can I produce an expression with a type of Func<obj>?,示出了一個單值lambda表達式自動轉換/轉換爲函數功能類型,然後在功能接受。具有多個參數轉換的F#函數的函數功能類型 - MathNet.Numerics

我與MathNet.Numerics庫工作,並可以通過集成確認此X^2介於0和10:

#r "../packages/MathNet.Numerics.3.20.0/lib/net40/MathNet.Numerics.dll" 
#r "../packages/MathNet.Numerics.FSharp.3.20.0/lib/net40/MathNet.Numerics.FSharp.dll" 

#load "Library1.fs" 
open Library3 

// Define your library scripting code here 

open MathNet.Numerics.Integration 

let integral = DoubleExponentialTransformation.Integrate((fun x -> x**2.0), 0.0, 10.0, 1.0) 

val answer : float = 333.3333333 

但是,我不能讓這個多值函數的工作。當我嘗試這個時,我得到一個類型錯誤。有沒有人知道這個工作?

open MathNet.Numerics.Optimization 
open MathNet.Numerics.LinearAlgebra.Double 

let newAnswer = BfgsSolver.Solve(DenseVector[|1.0, 1.0|], 
           (fun x y -> (x + y - 5.0) ** 2.0 + (y - x*x - 4.0) ** 2.0), 
           (fun x y -> DenseVector[| 2.0 * (x + y - 5.0) - 4.0 * x * (y - x*x - 4); 
                  2.0 * (x + y - 5.0) + 2.0 * (y - x*x - 4.0) |]) 
                  ) 

,我得到以下錯誤...

Script.fsx(20,34): error FS0193: Type constraint mismatch. The type 
    ''a -> 'b -> 'c'  
is not compatible with type 
    'System.Func<MathNet.Numerics.LinearAlgebra.Vector<float>,float>' 
+0

嘗試'樂趣(X,Y) - >',而不是'樂趣x和y - >'不是在PC上,將其轉換後回答。 – CaringDev

+0

@CaringDev我有點沮喪地發現,不能正常工作,至少使用'IEnumerable.Aggregate' – TheQuickBrownFox

+0

@TheQuickBrownFox很有可能......沒有做多少F#我的測試 - > C#的互動,不記得確切的情況我遇到了這最後。 – CaringDev

回答

3

您可以使用System.Func<_,_,_>()將函數轉換這樣的:

let newAnswer = BfgsSolver.Solve(DenseVector[|1.0, 1.0|], 
           (System.Func<_,_,_>(fun x y -> (x + y - 5.0) ** 2.0 + (y - x*x - 4.0) ** 2.0)), 
           (System.Func<_,_,_>(fun x y -> 
            DenseVector[| 2.0 * (x + y - 5.0) - 4.0 * x * (y - x*x - 4) 
                2.0 * (x + y - 5.0) + 2.0 * (y - x*x - 4.0) |]))) 

如果你發現自己需要這往往你可以使代碼少一點醜陋與助手:

let f2 f = System.Func<_,_,_> f 

UPDATE

望着Math.NET documentation for this method我現在看到,它實際上只有一個輸入需要的功能。也許你對Func<A, B>類型簽名感到困惑,但在這種情況下,A是輸入類型,而B是輸出類型。

具有一個輸入F#的功能被自動轉換爲Func<_,_>。我下載Math.NET這個很小的例子沒有給出編譯錯誤:

open MathNet.Numerics.Optimization 
open MathNet.Numerics.LinearAlgebra.Double 
BfgsSolver.Solve(DenseVector [||], (fun x -> x.[0]), (fun x -> x)) 

這表明,這個問題是不是與函數類型之間進行轉換,但使用功能與錯誤的元數。我應該從你原來的錯誤信息中看到這個!

+0

感謝您的回覆QBF。我仍然有型的問題,所以我投的一切在可能的情況: 讓F2 F = System.Func <_,_>˚F 讓newAnswer = BfgsSolver.Solve(A,B,(F2(樂趣(X:MathNet.Numerics。 LinearAlgebra.Vector ) - > [| 2.0 *(x。[0] + x。[1] - 5.0) - 4.0 * x。[0] *(x。[1] - x。[0] * x。 [0] - 4); 2.0 *(x。[0] + x。[1] - 5.0)+ 2.0 *(x。[1] - x。[0] * x。[0] - 4.0)|] ):MathNet.Numerics.LinearAlgebra.Vector ) )但它仍然給我的錯誤。你檢查你的解決方案是否有效?當我粘貼到Visual Studio中時,出現錯誤 – Shillington

+0

@ user2569729查看我的更新回答 – TheQuickBrownFox

+0

好的,但我最初的問題是如何使用多個參數,在您的答案中,您基本上使用了一個參數_,我的原始示例與集成函數。在我上面的回覆中,我嘗試使用變量轉換爲向量(因爲我的實際問題涉及多個參數),但是這給出了其他錯誤...您有任何其他的建議嗎? – Shillington

相關問題