Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. abstract class MyList {
  2.  
  3. /*
  4. 1. head -> returns the first element
  5. 2. tail -> returns the remaining elements
  6. 3. isEmpty -> is the list empty
  7. 4. add(int) -> new list with this element added
  8. 5. toString -> a string representation of this list
  9.  
  10. */
  11.  
  12. def head: Int
  13. def tail: MyList
  14. def isEmpty: Boolean
  15. def add(element: Int): MyList
  16. def printElements: String
  17. override def toString: String = "[" + printElements + "]"
  18.  
  19. }
  20.  
  21. object Empty extends MyList {
  22. def head: Int = throw new NoSuchElementException
  23. def tail: MyList = throw new NoSuchElementException
  24. def isEmpty: Boolean = true
  25. def add(element: Int): MyList = new Cons(element, this)
  26. def printElements: String = ""
  27.  
  28. }
  29.  
  30. class Cons(val h: Int, val t: MyList) extends MyList {
  31. def head: Int = h
  32. def tail: MyList = t
  33. def isEmpty: Boolean = true
  34. def add(element: Int): MyList = new Cons(element, this)
  35. def printElements: String = {
  36.  
  37. if(t.isEmpty) {
  38. println("hi")
  39. "" + h
  40. }
  41. else {
  42. println(h)
  43. h + " " + t.printElements
  44. }
  45. }
  46. }
  47.  
  48. object ListTest extends App {
  49. val my_list = new Cons(1, new Cons(2, new Cons(3, Empty)))
  50.  
  51. println(my_list.toString)
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement