加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在scala中获取通用(多态)lambda?

发布时间:2020-12-16 19:07:18 所属栏目:安全 来源:网络整理
导读:只是 Scala的一个简单例子: scala def f(x: Int) = xf: (x: Int)Intscala (f _)(5)res0: Int = 5 让我们通用: scala def f[T](x: T) = xf: [T](x: T)Tscala (f _)(5)console:9: error: type mismatch; found : Int(5) required: Nothing (f _)(5) ^ 我们来
只是 Scala的一个简单例子:

scala> def f(x: Int) = x
f: (x: Int)Int

scala> (f _)(5)
res0: Int = 5

让我们通用:

scala> def f[T](x: T) = x
f: [T](x: T)T

scala> (f _)(5)
<console>:9: error: type mismatch;
 found   : Int(5)
 required: Nothing
              (f _)(5)
                    ^

我们来看看Scala中多态方法的扩展:

scala> f _ 
res2: Nothing => Nothing = <function1>

与Haskell比较:

Prelude> let f x = x

Prelude> f 5
5
Prelude> f "a"
"a"
Prelude> :t f
f :: t -> t

Haskell确实推断了正确的类型[T] => [那里.

更现实的例子?

scala> identity _
res2: Nothing => Nothing = <function1>

更现实:

scala> def f[T](l: List[T]) = l.head
f: [T](l: List[T])T

scala> f _
res3: List[Nothing] => Nothing = <function1>

你不能为别人做别名 – 必须写你自己的功能.像[T,U](t:T,u:U)=> t – > u(make tuple)不可能用作值.更一般的 – 如果你想传递一些依赖于通用类型的lambda(例如,使用泛型函数,例如:创建列表,元组,以某种方式修改它们) – 你不能这样做.

那么如何解决这个问题呢?任何解决方法,解决方案或推理?

附:我使用术语多态lambda(而不是函数),因为函数只是命名为lambda

解决方法

只有JVM / Scala上的方法可以是通用的,而不是值.您可以制作一个匿名实例来实现一些界面(并为每个想要使用的类型重复它):

trait ~>[A[_],B[_]] { //exists in scalaz
  def apply[T](a: A[T]): B[T]
}

val f = new (List ~> Id) {
  def apply[T](a: List[T]) = a.head
}

或使用无形的“Poly”,它支持更复杂的类型.但是,这是一个限制,它需要解决.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读