我是F#和函数式编程的新手,需要一些帮助。我来自C#,所以我的思维方式仍然有点不同。如何将记录的属性声明为抽象函数
我需要将某些选项传递给一个函数,我正在使用这个记录。其中一个选项是延续功能单元 - >选件<'a>。我无法弄清楚如何定义记录类型。下面是我一直在尝试的一个例子。
type Func2<'a> = 'a -> 'a option
type ProcessOptions = {
func1: int -> int option
func2: Func2<int> // This works...
//func2: Func2<'a> // ... but this is what I'm trying to achieve - so that I can pass any Func2<'a> using this record.
}
let f1 a =
let r = Some a
printfn "f1: %A" r |> ignore
r
let f2 (a:'a) =
let r = Some a
printfn "f2: %A" r |> ignore
r
let f3 (processOptions:ProcessOptions) =
processOptions.func1(3) |> ignore
processOptions.func2 789 |> ignore
()
let f4 (processOptions:ProcessOptions) =
processOptions.func1(4) |> ignore
//processOptions.func2 "abc" |> ignore // as a result this does not work...
()
[<EntryPoint>]
let main argv =
f1(1) |> ignore
f2 123 |> ignore
f2 "abc" |> ignore
let fo = {
func1 = f1
func2 = f2
}
f3 fo
let fo1 = {
func1 = f1
func2 = f2
}
f4 fo1
0
感谢托马斯。我喜欢你的解决方案,因为它可以方便地将其他功能类型添加到记录中。 John的解决方案也可行,但我想我必须为ProcessOptions <...>添加更多的通用类型以获取其他通用类型。 –