代码之家  ›  专栏  ›  技术社区  ›  P Varga

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

  •  -4
  • P Varga  · 技术社区  · 6 年前

    一个人如何表达一个 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<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;
    }
    

    反过来说,一个 功能 那个 必须 是否返回新实例?

    // 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 ?


    斯卡拉


    *最初,这个问题是关于用打字稿来做这件事,但由于这是不可能的,我很好奇它是不是用另一种语言。

    如果该语言的类型系统无法表达此内容,请随意删除标记

    2 回复  |  直到 6 年前
        1
  •  4
  •   Andrey Tyukin    6 年前

    你可以-在斯卡拉。

    用返回的方法初始化 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)
                                                               ^
    

    这叫A singleton type, and is explained in the spec .

        2
  •  1
  •   Jörg W Mittag    6 年前

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

    a → a
    

    必须 是同一性函数:因为函数在 a ,它不可能知道 尤其是,它不可能知道如何构造 . 因为它也不具有世界价值或 IO monad或类似的东西,它不能从全局状态、数据库、网络、存储或终端获取值。它也不能删除该值,因为它必须返回 .

    因此,它唯一能做的就是返回 那是传进来的。

    推荐文章