登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-22 22:36:36 356浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何声明必须返回其参数之一的函数的签名? (任何语言*)》,聊聊,我们一起来看看吧!

问题内容

如何表达 function 的签名,该签名必须返回它接收(调用)的参数(或 this),在 typescript 中? 是否有一种编程语言可以做到这一点?*

// 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(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 必须返回一个新实例呢?

// example 3
function slice(a: t[], x, y): t[] // must return a new array

❌typescript

去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 吗?

✅scala

*最初,问题是关于在 typescript 中执行此操作,但由于这是不可能的,我很好奇它是否使用其他语言。

如果该语言的类型系统无法表达这一点,请随意删除标签


解决方案


你可以 - 在 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)
                                                           ^

这称为 singleton type, and is explained in the spec

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

a → a

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

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>