0

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

1
  • in_shuffle is working perfectly fine. But facing issues only when I call the function as a parameter. Commented Feb 13, 2020 at 15:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Got you. But @Mario Isn't it the complex method to pass the function as a parameter???
It would be more usual to put the function argument by itself so def n_shuffle[T](list: List[T], n: Int)(f: (List[T], Int) => List[T]) to make the call look better when using a lambda.
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.