我試圖探索F#的動態功能,以適應靜態類型系統無法表達某些功能的情況。因此,我試圖爲(比如)Option
類型創建一個mapN
函數,但我在創建具有動態數量參數的函數時遇到問題。我已經試過:F#中的動態函數
let mapN<'output> (f : obj) args =
let rec mapN' (state:obj) (args' : (obj option) list) =
match args' with
| Some x :: xs -> mapN' ((state :?> obj -> obj) x) xs
| None _ :: _ -> None
| [] -> state :?> 'output option
mapN' f args
let toObjOption (x : #obj option) =
Option.map (fun x -> x :> obj) x
let a = Some 5
let b = Some "hi"
let c = Some true
let ans = mapN<string> (fun x y z -> sprintf "%i %s %A" x y z) [a |> toObjOption; b |> toObjOption; c |> toObjOption]
(這需要傳遞的功能,並在同一時間將一個參數),它編譯,但隨後在運行時,我得到以下幾點:
System.InvalidCastException: Unable to cast object of type '[email protected]' to type
'Microsoft.FSharp.Core.FSharpFunc`2[System.Object,System.Object]'.
我知道或者爲選項創建計算表達式,或者定義map2
到map5
左右,但我特別想探索F#的動態功能以查看這樣的事情是否可行。
這僅僅是一個無法在F#中完成的概念,還是存在我失蹤的方法?
感謝您解釋爲什麼我的解決方案無法正常工作以及如何使其工作。我同意動態解決方案相當粗糙,不適合生產。這並不改變我對F#的看法,我只是對那裏的能力感到好奇。 –