小编Rég*_*les的帖子

结构类型细化和类型相等

我偶然发现了Type.=:=在应用于类型再生时的令人费解的行为.考虑:

import reflect.runtime.universe._
type T1 = AnyRef {
  def apply( name: String ): Unit
  def foo: String
}

type Base = { def apply( name: String ): Unit }
type T2 = Base {
  def foo: String
}
Run Code Online (Sandbox Code Playgroud)

由于Base是一种细化的别名,我会预计,通过将会员进一步完善它foo会产生就好像我所定义的相同类型fooBase.

或者换句话说,我希望T1并且T2表示完全等同的类型.

在大多数情况下,scalac似乎同意.通过示例,我可以传递一个实例T2所在的实例T1:

def f( x: T1 ){}
f( null: T2 ) // scalac does not complain here
Run Code Online (Sandbox Code Playgroud)

反之亦然:

def g( x: T2 ){} …
Run Code Online (Sandbox Code Playgroud)

reflection scala structural-typing

6
推荐指数
1
解决办法
202
查看次数

Scala中高效的二维数组列提取

例如,考虑一个二维数组

scala> val a = Array.tabulate(2,3){_+_}
a: Array[Array[Int]] = Array(Array(0, 1, 2), Array(1, 2, 3))
Run Code Online (Sandbox Code Playgroud)

如何定义一个函数

def getCol(ith: Int, a: Array[Array[Int]]): Array[Int]
Run Code Online (Sandbox Code Playgroud)

提供

val col2 = getCol(2, a)
col2: Array[Int] = Array(1,2)
Run Code Online (Sandbox Code Playgroud)

一种简单而低效的方法包括

def getCol(ith: Int, a: Array[Int]): Array[Int] = {
  val t = a.transpose
  t(ith)
}
Run Code Online (Sandbox Code Playgroud)

因此,还要问更有效的方法.

arrays collections scala

5
推荐指数
1
解决办法
2734
查看次数

根据元组元素过滤列表

我有一个List [(Int,Int)].

防爆.

val a = List((1,2),(2,3),(1,4),(2,4),(5,6),(4,5),(1,8))
Run Code Online (Sandbox Code Playgroud)

我想过滤这个列表,以便如果几个元组具有相同的第一个元素(相同的值_1),那么只保留第一个元组.

所以这里预期的答案是:

val ans=List((1,2),(2,3),(5,6),(4,5))
Run Code Online (Sandbox Code Playgroud)

作为第一个元素(1,2)1和同样适用于(1,4)(1,8),我们只保留第一次出现((1,2))而忽略其他((1,4)(1,8)).

我怎样才能做到这一点?

scala

0
推荐指数
1
解决办法
1910
查看次数