// LIST FUNctions or FUN with LISTs :) // Function taking 1 argument class Function1 { method invoke(x : Int) : Int = false // abstract } class Pow2 extends Function1 { method invoke(x : Int) : Int = x * x } class Neg extends Function1 { method invoke(x : Int) : Int = 0 - x } class List { method isEmpty() : Int = true method append(that : List) : List = that method contains(x: Int) : Int = false method length() : Int = 0 method isSubsetOf(that: List) : Int = true method print() : Int = true method reverse() : List = this method map(f : Function1) : List = this } class Nil extends List {} class Cons extends List { field head : Int = 0 field tail : List = new Nil field separator : Int = 32 // ' ' method isEmpty(): Int = false method print(): Int = { printInt(this.head); printChar(this.separator) return this.tail.print() } method contains(x: Int): Int = if this.head == x then true else this.tail.contains(x) method append(that: List): List = { this.{ tail = this.tail.append(that) } return this } method length(): Int = 1 + this.tail.length() method isSubsetOf(that: List) : Int = if that.contains(this.head) then this.tail.isSubsetOf(that) else false method reverse() : List = this.tail.reverse().append(new Cons.{ head = this.head ; tail = new Nil }) method map(f : Function1) : List = new Cons.{ head = f.invoke(this.head); tail = this.tail.map(f) } } class Main { field a : List = new Cons.{ head = 4 ; tail = new Cons.{ head = 7 ; tail = new Cons.{ head = 1 ; tail = new Cons.{ head = 6 ; tail = new Cons.{ head = 2 ; tail = new Cons.{ head = 3 ; tail = new Cons.{ head = 5 ; tail = new Nil }}}}}}} method go() : Int = { this.a.print(); printChar(10); this.a.reverse().print(); printChar(10); this.a.map(new Pow2).print(); printChar(10); this.a.map(new Neg).print() return true } } new Main.go()