【问题标题】:Getting Type Mismatch error in function as parameter in scala在函数中获取类型不匹配错误作为scala中的参数
【发布时间】:2020-05-29 08:40:25
【问题描述】:

当我通过传递函数作为参数从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)
}

这是我在main 中调用n_shuffle 的方式

print( n_shuffle(in_shuffle, (1 to 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) )

我们将不胜感激任何帮助。谢谢

【问题讨论】:

  • in_shuffle 工作正常。但只有当我将函数作为参数调用时才会遇到问题。

标签: scala function functional-programming


【解决方案1】:

尝试多个参数列表来帮助类型推断

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 to 8).toList 得到它,但这是第二个参数。

【讨论】:

  • 知道了。但是@Mario不就是把函数作为参数传递的复杂方法吗???
  • 将函数参数单独放置会更常见,因此def n_shuffle[T](list: List[T], n: Int)(f: (List[T], Int) => List[T]) 可以在使用 lambda 时使调用看起来更好。
【解决方案2】:

似乎这种情况下的推理没有按预期工作。强制 in_shuffle[Int] 方法中的类型起到了作用。

试试这个吧。

print(n_shuffle(in_shuffle[Int], (1 to 8).toList, 2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多