Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- abstract class MyList {
- /*
- 1. head -> returns the first element
- 2. tail -> returns the remaining elements
- 3. isEmpty -> is the list empty
- 4. add(int) -> new list with this element added
- 5. toString -> a string representation of this list
- */
- def head: Int
- def tail: MyList
- def isEmpty: Boolean
- def add(element: Int): MyList
- def printElements: String
- override def toString: String = "[" + printElements + "]"
- }
- object Empty extends MyList {
- def head: Int = throw new NoSuchElementException
- def tail: MyList = throw new NoSuchElementException
- def isEmpty: Boolean = true
- def add(element: Int): MyList = new Cons(element, this)
- def printElements: String = ""
- }
- class Cons(val h: Int, val t: MyList) extends MyList {
- def head: Int = h
- def tail: MyList = t
- def isEmpty: Boolean = true
- def add(element: Int): MyList = new Cons(element, this)
- def printElements: String = {
- if(t.isEmpty) {
- println("hi")
- "" + h
- }
- else {
- println(h)
- h + " " + t.printElements
- }
- }
- }
- object ListTest extends App {
- val my_list = new Cons(1, new Cons(2, new Cons(3, Empty)))
- println(my_list.toString)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement