在Scala中的泛型编程 [英] Generic Programming in Scala

查看:98
本文介绍了在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 它被称为阴影

<


  1. Scala类型参数错误,不是类型参数的成员

  2. Scala,Extend具有通用特征的对象

  3. Scala中的泛型类型推断


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. Replace loop[T] with loop.

With loop[T] you are creating new type parameter with name T, so T outside loop method and T in loop method are different type aliases with the same name.

It's called shadowing.

See these answers for similar problems:

  1. Scala type parameter error, not a member of type parameter
  2. Scala, Extend object with a generic trait
  3. Generic type inference in Scala

这篇关于在Scala中的泛型编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆