Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. Hi mate, working in intelli J following a pdf tute on case classes, just can't work out why the compiler is complaining about where I've done my type definition?
  2.  
  3. /**
  4. * Created by jim on 31/10/2014.
  5. */
  6. abstract class Tree
  7. case class Sum(l: Tree, r: Tree) extends Tree
  8. case class Var(n: String) extends Tree
  9. case class Const(v: Int) extends Tree
  10.  
  11. type Environment = String => Int
  12.  
  13. def eval(t: Tree, env: Environment): Int = t match {
  14. case Sum(l, r) => eval(l, env) + eval(r, env)
  15. case Var(n) => env(n)
  16. case Const(v) => v
  17. }
  18.  
  19. def derive(t: Tree, v: String): Tree = t match {
  20. case Sum(l, r) => Sum(derive(l, v), derive(r,v))
  21. case Var(n) if (v == n) => Const(1)
  22. case _ => Const (0)
  23. }
  24.  
  25. def main(args: Array[String]): Unit = {
  26. val exp: Tree = Sum(Sum(Var("x"), Var("x")), Sum(Const(7), Var("y")))
  27. val env: Environment = { case "x" => 5 case "y" => 7 }
  28. println("Expression: " + exp)
  29. println("Evaluation with x=5, y=7: " + eval(exp, env))
  30. println("Derivative relative to x:\n " + derive(exp, "x"))
  31. println("Derivative relative to y:\n" + derive(exp, "y"))
  32. }
  33.  
  34.  
  35. Compiler errors are:
  36.  
  37. Error:(8, 1) expected class or object definition
  38. type Environment = String => Int
  39. ^
  40. Error:(10, 1) expected class or object definition
  41. def eval(t: Tree, env: Environment): Int = t match {
  42. ^
  43. Error:(16, 1) expected class or object definition
  44. def derive(t: Tree, v: String): Tree = t match {
  45. ^
  46. Error:(22, 1) expected class or object definition
  47. def main(args: Array[String]): Unit = {
  48. ^
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement