Scala元组的通用“地图”功能?
发布时间:2020-12-16 19:00:03 所属栏目:安全 来源:网络整理
导读:我想使用一个返回类型为R的单个函数来映射 Scala元组(或三元组,…)的元素.结果应该是一个元组(或三元组,…),元素为R. 好的,如果元组的元素来自相同的类型,映射不是一个问题: scala implicit def t2mapper[A](t: (A,A)) = new { def map[R](f: A = R) = (f(t
我想使用一个返回类型为R的单个函数来映射
Scala元组(或三元组,…)的元素.结果应该是一个元组(或三元组,…),元素为R.
好的,如果元组的元素来自相同的类型,映射不是一个问题: scala> implicit def t2mapper[A](t: (A,A)) = new { def map[R](f: A => R) = (f(t._1),f(t._2)) } t2mapper: [A](t: (A,A))java.lang.Object{def map[R](f: (A) => R): (R,R)} scala> (1,2) map (_ + 1) res0: (Int,Int) = (2,3) 但是也可以使这个解决方案是通用的,即以相同的方式映射包含不同类型元素的元组? 例: class Super(i: Int) object Sub1 extends Super(1) object Sub2 extends Super(2) (Sub1,Sub2) map (_.i) 应该回来 (1,2): (Int,Int) 但是我找不到解决方案,以便映射函数确定Sub1和Sub2的超类型.我试图使用类型边界,但我的想法失败了: scala> implicit def t2mapper[A,B](t: (A,B)) = new { def map[X >: A,X >: B,R](f: X => R) = (f(t._1),f(t._2)) } <console>:8: error: X is already defined as type X implicit def t2mapper[A,f(t._2)) } ^ <console>:8: error: type mismatch; found : A required: X Note: implicit method t2mapper is not applicable here because it comes after the application point and it lacks an explicit result type implicit def t2mapper[A,f(t._2)) } 这里X>:B似乎覆盖X> ;: A. Scala不支持关于多种类型的类型边界?如果是的,为什么不呢? 解决方法
我认为这是你要找的:
implicit def t2mapper[X,A <: X,B <: X](t: (A,B)) = new { def map[R](f: X => R) = (f(t._1),f(t._2)) } scala> (Sub1,Sub2) map (_.i) res6: (Int,Int) = (1,2) 一个更“功能”的方法可以通过两个独立的功能: implicit def t2mapper[A,B)) = new { def map[R](f: A => R,g: B => R) = (f(t._1),g(t._2)) } scala> (1,"hello") map (_ + 1,_.length) res1: (Int,5) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |