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.
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
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.
It seems that the inference in this case does not work as expected. Forcing the type in in_shuffle[Int] method did the trick.
Try this instead.
print(n_shuffle(in_shuffle[Int], (1 to 8).toList, 2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.