Scala:实现通用折叠

时间:2017-05-30 16:57:47

标签: scala

我不明白为什么折叠不能编译。谁能给我一个线索?

sealed trait ListG[A] {

  def fold[A,B](end: B, f: (A,B) => B): B = this match {
    case End() => end
    case Cons(hd,tl) => f(hd, tl.fold(end,f))
  }
}

错误:(20,28)类型不匹配;  发现:hd.type(底层类型A)  要求:A     案例缺点(hd,tl)=> f(hd,tl.fold(end,f))                           ^     最终案例类EndA扩展ListG [A]     最终案例类Cons [A](hd:A,tl:ListG [A])扩展ListG [A]

2 个答案:

答案 0 :(得分:4)

public class FinalProject1 implements Runnable { private Scanner keyboard = new Scanner(System.in); private int num = random(); public static void main(String[] args) { System.out.println("Number Guessing Game 1-1000\nGuess a number"); new Thread(new FinalProject1()).start(); } public static int random() { return (int) (1000 * Math.random() + 1); } @Override public void run() { String inputString = this.keyboard.nextLine(); int input = Integer.parseInt(inputString); if (input > this.num) { System.out.println("Guess a lower number"); new Thread(this).start(); } else if (input < this.num) { System.out.println("Guess a higher number"); new Thread(this).start(); } else if (this.num == input) { System.out.println("You Win"); } } } 函数上定义其他类型参数A时,您为ListG的阴影类型参数A

答案 1 :(得分:0)

添加类型归属似乎可以解决问题。

case Cons(hd:A, tl) => ...
            ^^

有关于类型擦除的警告,但它确实编译并且似乎正在运行。