Created
February 5, 2015 14:46
-
-
Save xudifsd/f81506ca49a284327388 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| object Hi { | |
| def main(args: Array[String]):Unit = { | |
| var list:List[Any] = List.newList("aaa") | |
| val fn = (node: ListNode[Any]) => | |
| println(node.data) | |
| list = list.insert("bbb") | |
| List.travse(list, fn) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| case class ListNode[+T](data: T, next: Option[ListNode[T]]) object List { | |
| def newList[T](data: T) = newListFromNode(new ListNode(data, None)) | |
| def newListFromNode[T](node: ListNode[T]) = new List(node) | |
| private def travse_iter[A](head:Option[ListNode[A]], fn: (ListNode[A]) => Unit): Unit = { | |
| head match { | |
| case Some(node) => { | |
| fn(node) | |
| List.travse_iter(node.next, fn) | |
| } | |
| case None => | |
| } | |
| } | |
| def travse[A](l: List[A], fn: (ListNode[A]) => Unit): Unit = { | |
| travse_iter(Some(l.head), fn) | |
| } | |
| } | |
| class List[+T] (node: ListNode[T]) { | |
| val head = node | |
| def insert[A](data: A) = List.newListFromNode(new ListNode(data, Some(head))) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment