F# - 我可以使用类型名称作为默认构造函数吗?

woo*_*ngs 6 f#

要创建我的班级序列,

type MyInt(i:int) =
    member this.i = i

[1;2;3] |> Seq.map(fun x->MyInt(x))
Run Code Online (Sandbox Code Playgroud)

哪里fun x->MyInt(x)似乎是多余的.如果我能写的话会更好Seq.map(MyInt)

但是我不能.我能想到的一个解决方法是定义一个单独的函数

let myint x = MyInt(x)
[1;2;3] |> Seq.map(myint)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

Dan*_*iel 9

如果无偿的黑客不打扰你,你可以这样做:

///functionize constructor taking one arg
let inline New< ^T, ^U when ^T : (static member ``.ctor`` : ^U -> ^T)> arg =
  (^T : (static member ``.ctor`` : ^U -> ^T) arg)

type MyInt(i: int) =
  member x.i = i

[0..9] |> List.map New<MyInt, _>
Run Code Online (Sandbox Code Playgroud)

编辑:正如kvb指出的那样,可以使用更简单(并且更少hacky)的签名:

let inline New x = (^t : (new : ^u -> ^t) x)
Run Code Online (Sandbox Code Playgroud)

注意,这会切换类型args,所以它变成了New<_, MyInt>.


pad*_*pad 7

简而言之,没有.

对象构造函数不是F#中的第一类函数.这是不使用类的另一个原因,在这里使用歧视联盟更好:

type myInt = MyInt of int
let xs = [1;2;3] |> Seq.map MyInt
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢显式lambdas,则序列表达式在您的示例中看起来更好:

let xs = seq { for x in [1;2;3] -> MyInt x }
Run Code Online (Sandbox Code Playgroud)

或者,您的解决方法是一个很好的解决方案.