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

如何表达 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 2

function 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 3

function 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) T

func main() {

  var mutate returnsSameIntSlice = func(a *[]int) *[]int {

    b := []int{2}

    /* Would this compile? */ return &b

    /* This should */         return a

  }

}  

C++20?

以上可以表示为 C++ 吗concept?


江户川乱折腾
浏览 83回答 2
2回答

神不在的星期二

你可以 - 在 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)                                                           ^这称为单例类型,并在规范中进行了解释。

慕尼黑5688855

在具有参数多态性的语言中,任何类型的函数a&nbsp;→&nbsp;a必须是恒等函数:因为该函数在 中是多态的a,所以它不可能知道关于 的任何信息a,特别是它不可能知道如何构造一个a.&nbsp;由于它也不采用世界值或IOmonad 或等价物,因此它无法从全局状态、数据库、网络、存储或终端获取值。它也不能删除该值,因为它必须返回一个a.因此,它唯一能做的就是返回a传入的内容。
打开App,查看更多内容
随时随地看视频慕课网APP