亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何聲明必須返回其參數之一的函數的簽名?(任何語言*)

如何聲明必須返回其參數之一的函數的簽名?(任何語言*)

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 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號