将F#管道符号与对象构造函数一起使用

时间:2021-11-29 19:11:37

I'm trying to figure out the correct syntax to use the pipe operator |> into the creation of an object. Currently I'm using a static member to create the object and just piping to that. Here is the simplified version.

我正在试图找出使用管道运算符|>进入对象创建的正确语法。目前我正在使用静态成员来创建对象,并且只是为了管道。这是简化版。

type Shape = 
    val points : Vector[]

    new (points) =
        { points = points; }

    static member create(points) =
        Shape(points)

    static member concat(shapes : Shape list) =
        shapes
            |> List.map (fun shape -> shape.points)
            |> Array.concat
            |> Shape.create

What I want to do ...

我想做的事 ...

    static member concat(shapes : Shape list) =
        shapes
            |> List.map (fun shape -> shape.points)
            |> Array.concat
            |> (new Shape)

Is something like this possible? I don't want to duplicate code by repeating my constructor with the static member create.

这样的事情可能吗?我不想通过使用静态成员create重复我的构造函数来复制代码。

Update Constructors are first-class functions as of F# 4.0

更新构造函数是F#4.0的一流函数

In F# 4.0 the correct syntax is.

在F#4.0中,正确的语法是。

    static member concat(shapes : Shape list) =
        shapes
            |> List.map (fun shape -> shape.points)
            |> Array.concat
            |> Shape

2 个解决方案

#1


There's always

(fun args -> new Shape(args))

#2


Apparently, object constructors aren't composable. Discriminated union constructors don't seem to have this problem:

显然,对象构造函数不可组合。被区分的联合构造函数似乎没有这个问题:

> 1 + 1 |> Some;;
val it : int option = Some 2

If you want to use the pipeline, Brian's answer is probably best. In this case, I'd consider just wrapping the entire expression with Shape( ).

如果你想使用管道,Brian的答案可能是最好的。在这种情况下,我会考虑用Shape()包装整个表达式。

#1


There's always

(fun args -> new Shape(args))

#2


Apparently, object constructors aren't composable. Discriminated union constructors don't seem to have this problem:

显然,对象构造函数不可组合。被区分的联合构造函数似乎没有这个问题:

> 1 + 1 |> Some;;
val it : int option = Some 2

If you want to use the pipeline, Brian's answer is probably best. In this case, I'd consider just wrapping the entire expression with Shape( ).

如果你想使用管道,Brian的答案可能是最好的。在这种情况下,我会考虑用Shape()包装整个表达式。