为了账号安全,请及时绑定邮箱和手机立即绑定

如何声明必须返回其参数之一的函数的签名?(任何语言*)

如何声明必须返回其参数之一的函数的签名?(任何语言*)

Go
江户川乱折腾 2023-06-05 17:37:05
如何表达 a 的签名,function它必须this返回它接收(被调用)的参数(或),在打字稿中?有没有一种编程语言可以做到这一点?*// In TypeScript (or consider it pseudo-code)class C {  // EXAMPLE 1 – Not polymorphic  chainable(x): this                 // MUST not only return some C,  {}                                 // but the same instance it was called on}// EXAMPLE 2function mutate<T>(a: T[], x): T[]   // MUST return a, not a new Array{  /* So that this doesn't compile */ return Array.from(a);  /* But this is OK */               return a;}function相反, a必须返回一个新实例怎么样?// EXAMPLE 3function slice<T>(a: T[], x, y): T[] // MUST return a new Array❌打字稿走2?以下会contract实现上述目标吗?contract referentiallyIdentical(f F, p P) {  f(p) == p  v := *p}type returnsSameIntSlice(type T, *[]int referentiallyIdentical) Tfunc main() {  var mutate returnsSameIntSlice = func(a *[]int) *[]int {    b := []int{2}    /* Would this compile? */ return &b    /* This should */         return a  }}  C++20?以上可以表示为 C++ 吗concept?
查看完整描述

2 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

你可以 - 在 Scala 中。


类的方法返回this.type:


class C {

  var x = 0 


  /** Sets `x` to new value `i`, returns the same instance. */

  def with_x(i: Int): this.type = {

    x = i

    this   // must be `this`, can't be arbitrary `C`

  } 

}

保证返回完全相同的数组的就地排序(这里并没有真正排序任何东西):


def sortInPlace[A: Ordered](arr: Array[A]): arr.type = {

  /* do fancy stuff with indices etc. */

  arr

}

如果您尝试返回不同的数组,


def badSortInPlace(arr: Array[Int]): arr.type = Array(1, 2, 3) // won't compile

你会在编译时得到一个错误:


error: type mismatch;

found   : Array[Int]

required: arr.type

      def badSortInPlace(arr: Array[Int]): arr.type = Array(1, 2, 3)

                                                           ^

这称为单例类型,并在规范中进行了解释。



查看完整回答
反对 回复 2023-06-05
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

在具有参数多态性的语言中,任何类型的函数

a → a

必须是恒等函数:因为该函数在 中是多态的a,所以它不可能知道关于 的任何信息a,特别是它不可能知道如何构造一个a. 由于它也不采用世界值或IOmonad 或等价物,因此它无法从全局状态、数据库、网络、存储或终端获取值。它也不能删除该值,因为它必须返回一个a.

因此,它唯一能做的就是返回a传入的内容。


查看完整回答
反对 回复 2023-06-05
  • 2 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信