在Scala中的泛型编程 [英] Generic Programming in Scala
问题描述
我试图写我自己的累积版本(fold)我想知道为什么我正在运行如下所示:
def accumulate [T](list:List [T],initial:T,f: (T,T)=> T):T = {
@tailrec def loop [T](list:List [T],accum:T):T =
if(list.length = = 0)
accum
else {
val head:T = list.head
val res:T = f(accum,head)
loop [T]( list.tail,res)
}
loop(list,initial)
}
我收到以下错误:
type mismatch;
found:accum.type(带底层类型T)
required:T
val res:T = f(accum,head)
^
$ b我看不出类型不匹配,因为一切都是T类型。
任何想法/帮助将不胜感激。
Blair
解决方案您应该从
loop
方法中删除类型参数。将loop [T]
替换为loop
。
loop [T]
您正在创建名称T
的新类型参数,所以T
循环
方法和T
在循环
方法是具有相同名称的不同类型别名。
$ b 它被称为阴影。
<
Hi all I am fairly new to Scala coming from C#.
I am attempting to write my own version of accumulate ( fold) I am wondering why I am running into some issues with the following:
def accumulate[T](list : List[T], initial: T, f: (T, T) => T) : T = { @tailrec def loop[T](list: List[T], accum: T) : T = if(list.length == 0) accum else{ val head : T = list.head val res : T = f(accum,head) loop[T](list.tail, res) } loop(list,initial) }
I am getting the following error:
type mismatch; found : accum.type (with underlying type T) required: T val res : T = f(accum,head) ^
I cant see how I have a type mismatch considering everything is type T.
Any thoughts / help would be appreciated.
Blair
解决方案You should just remove type parameter from
loop
method. Replaceloop[T]
withloop
.With
loop[T]
you are creating new type parameter with nameT
, soT
outsideloop
method andT
inloop
method are different type aliases with the same name.It's called shadowing.
See these answers for similar problems:
- Scala type parameter error, not a member of type parameter
- Scala, Extend object with a generic trait
- Generic type inference in Scala
这篇关于在Scala中的泛型编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!