函数字面量可以在 Scala 中使用类型参数吗? [英] Can a function literal use type parameter in Scala?
问题描述
给定以下多态方法 removeAt
的定义:
def removeAt[T](n: Int, ts: Seq[T]): (Seq[T], T) = ???
如何声明一个类似 removeAt
的函数列表?函数字面量可以使用类型参数吗?
如何使以下内容可编译并能够包含 removeAt
?
List[(Int, Seq[_]) =>(Seq[_], _)](removeAt)
更新:为什么下面的工作正常,所以我可以foreach
遍历列表并执行函数?这正是我首先需要的.
val 解决方案 = Seq[(Int, Seq[Any]) =>(Seq[Any], Any)](删除在)
博文 shapeless 中的一流多态函数值 (1 of 3) — Scala 中的函数值 似乎暗示在标准"Scala 中没有办法拥有多态函数值:><块引用>
我们可以有一流的单态函数值,我们可以有二等的多态方法,但我们不能有一流的多态函数值......至少我们不能用标准Scala 定义.
看起来我们需要一个像 shapeless 这样的库.
Given the following definition of a method removeAt
that's polymorphic:
def removeAt[T](n: Int, ts: Seq[T]): (Seq[T], T) = ???
How can I declare a list of removeAt
-like functions? Can a function literal use type parameter?
How can I make the following compilable and able to contain removeAt
?
List[(Int, Seq[_]) => (Seq[_], _)](removeAt)
UPDATE: Why does the following work fine so I can foreach
over the list and execute the functions? That's exactly what I needed in the first place.
val solutions = Seq[(Int, Seq[Any]) => (Seq[Any], Any)](
removeAt
)
The blog post First-class polymorphic function values in shapeless (1 of 3) — Function values in Scala seems to imply that there's no way in "standard" Scala to have polymorphic function values:
We can have first-class monomorphic function values and we can have second-class polymorphic methods, but we can't have first-class polymorphic function values ... at least we can't with the standard Scala definitions.
It looks like we need a library like shapeless.
这篇关于函数字面量可以在 Scala 中使用类型参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!