我可以在F#中使用管道运算符将参数传递给构造函数吗? [英] Can I use the pipeline operator in F# to pass an argument to a constructor?

查看:78
本文介绍了我可以在F#中使用管道运算符将参数传递给构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码将字符串反向:

let reverse (s : string) = new string(s.ToCharArray() |> Array.rev)

可以使用管道运算符将必需的参数传递给string()构造函数来重写此代码吗?例如,这似乎更惯用:

Can this be rewritten using the pipeline operator to pass the required argument to the string() constructor? For example, this seems more idiomatic:

// Doesn't compile:
let reverse (s : string) = s.ToCharArray() |> Array.rev |> new string

类似地,为什么不能以以下方式使用string运算符?

Similarly, why can't I use the string operator in the following way?

let reverse2 (s : string) = s.ToCharArray() |> Array.rev |> string

这里正在起作用:

> reverse2 "foo" ;;
val it : string = "System.Char[]"

它返回类型而不是"oof".

It returns the type rather than "oof".

推荐答案

否,管道运算符只能与F#函数一起使用,不能与类构造函数,成员方法或静态方法一起使用.原因是这些方法支持的重载会使F#的类型推断变得复杂.但是,如果您确实想使用管道,则可以将char Array的每个元素映射到一个String,然后将该序列管道输送到Seq.concat "":

No, the pipe operator may only be used with F# functions, it cannot be used with class constructors, member methods or static methods. The reason being that the overloading supported by these kinds of methods would complicate F#'s type inference. However, if you really want to use piping, you could map each element of the char Array to a String and then pipe that sequence into Seq.concat "":

s.ToCharArray() |> Array.rev |> Seq.map(string) |> String.concat ""

或者您可以将字符串构造函数调用包装在F#方法中:

Or you could wrap the string constructor call in an F# method:

let stringCArrCtor (carr: char[]) =
    new string(carr)

s.ToCharArray() |> Array.rev |> stringCArrCtor

并回答您的最后一个问题,

And to answer your last question,

s.ToCharArray() |> Array.rev |> string

不能使用,因为它等同于

can't be used because it is equivalent to

(s.ToCharArray() |> Array.rev).ToString()

并且不重写Array ToString()方法,因此它只返回默认的反射类型名称.

and the Array ToString() method is not overridden so it just returns the default reflected type name.

这篇关于我可以在F#中使用管道运算符将参数传递给构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆