将函数中的类型不匹配错误作为scala中的参数获取
当我通过传递函数作为参数从将函数中的类型不匹配错误作为scala中的参数获取,scala,function,functional-programming,Scala,Function,Functional Programming,当我通过传递函数作为参数从n\u shuffle调用in\u 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], Li
n\u shuffle
调用in\u 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)
}
下面是我如何在main
中调用
n\u shuffle
print(n\u shuffle(in\u shuffle,(1到8)。toList,2))
我得到的错误是
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) )
任何帮助都将不胜感激。谢谢尝试使用多个参数列表来辅助类型推断
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)
或者提供显式类型注释
n_shuffle(in_shuffle[Int], (1 to 8).toList, 2)
n_shuffle[Int](in_shuffle, (1 to 8).toList, 2)
编译器无法推断中第一个参数的类型的原因
def n_shuffle[T](f: (List[T], Int) => List[T], list: List[T], n: Int)
是因为它将从
(1到8)中获取它。toList
但是这是第二个参数。尝试使用多个参数列表来辅助类型推断
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)
或者提供显式类型注释
n_shuffle(in_shuffle[Int], (1 to 8).toList, 2)
n_shuffle[Int](in_shuffle, (1 to 8).toList, 2)
编译器无法推断中第一个参数的类型的原因
def n_shuffle[T](f: (List[T], Int) => List[T], list: List[T], n: Int)
这是因为它将从
(1到8)中得到它。toList
,但是这是第二个参数。在这种情况下,推理似乎没有按预期工作。强制输入in_shuffle[Int]方法就成功了
试试这个
print(n_shuffle(in_shuffle[Int], (1 to 8).toList, 2))
看来,这种情况下的推论并不像预期的那样有效。强制输入in_shuffle[Int]方法就成功了 试试这个
print(n_shuffle(in_shuffle[Int], (1 to 8).toList, 2))
in_shuffle
运行得非常好。但是,只有当我将函数作为参数调用时,才会遇到问题。in_shuffle
工作得非常好。但是只有当我把函数作为参数调用时才会遇到问题。明白了。但是@Mario将函数作为参数传递不是一种复杂的方法吗???更常见的做法是将函数参数单独放置,以便def n_shuffle[t](list:list[t],n:Int)(f:(list[t],Int)=>list[t])
在使用lambda时使调用看起来更好。明白了吗。但是@Mario将函数作为参数传递不是一种复杂的方法吗???更常见的做法是将函数参数单独放置,以便在使用lambda时使调用看起来更好。