[英]Getting Type Mismatch error in function as parameter in scala
I am facing some issues of type mismatch in scala when I am calling the in_shuffle
method from n_shuffle
by passing a function as a parameter.当我通过传递函数作为参数从
n_shuffle
调用in_shuffle
方法时,我在 scala 中遇到了一些类型不匹配的问题。
def in_shuffle[T](original: List[T], restrict_till:Int= -1):List[T]={
require(original.size % 2 == 0, "In shuffle requires even number of elements")
def shuffle(t: (List[T], List[T])): List[T] =
t._2 zip t._1 flatMap { case (a, b) => List(a, b) }
def midpoint(l: List[T]): Int = l.size / 2
@annotation.tailrec
def loop(current: List[T], restrict_till:Int, count:Int=0): List[T] = {
if (original == current || restrict_till == count) current
else{
val mid = midpoint(current)
val shuffled_ls = shuffle(current.splitAt(mid))
loop(shuffled_ls, restrict_till, count+1)
}
}
loop(shuffle(original.splitAt(midpoint(original))), restrict_till, 1)
}
def n_shuffle[T](f: (List[T], Int) => List[T], list:List[T], n:Int):List[T]={
println("Inside Sub-function")
f(list, n)
}
Here is how i'm calling n_shuffle
in main
这是我在
main
调用n_shuffle
的方式print( n_shuffle(in_shuffle, (1 to 8).toList, 2) )
Error I am getting is我得到的错误是
Error:(161, 22) type mismatch;
found : (List[Nothing], Int) => List[Nothing]
required: (List[Int], Int) => List[Int]
print( n_shuffle(in_shuffle, (1 to 8).toList, 2) )
Any help will highly be appreciated.任何帮助将不胜感激。 Thanks
谢谢
Try multiple parameter lists to aid type inference尝试多个参数列表来帮助类型推断
def n_shuffle[T](list: List[T], n: Int)(f: (List[T], Int) => List[T]): List[T]
n_shuffle((1 to 8).toList, 2)(in_shuffle)
or provide explicit type annotation或提供显式类型注释
n_shuffle(in_shuffle[Int], (1 to 8).toList, 2)
n_shuffle[Int](in_shuffle, (1 to 8).toList, 2)
The reason compiler is unable to infer type of the first parameter in编译器无法推断第一个参数的类型的原因
def n_shuffle[T](f: (List[T], Int) => List[T], list: List[T], n: Int)
is because it would get it from (1 to 8).toList
however that is the second argument.是因为它会从
(1 to 8).toList
获取它,但是这是第二个参数。
It seems that the inference in this case does not work as expected.似乎这种情况下的推理没有按预期工作。 Forcing the type in in_shuffle[Int] method did the trick.
强制 in_shuffle[Int] 方法中的类型可以解决问题。
Try this instead.试试这个。
print(n_shuffle(in_shuffle[Int], (1 to 8).toList, 2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.