Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created October 29, 2008 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymnk/20645 to your computer and use it in GitHub Desktop.
Save ymnk/20645 to your computer and use it in GitHub Desktop.
import scala.xml.Node
import scala.collection.immutable.Set
import scala.util.Sorting
/**
* This program will demonstrate how to use scala.util.Sorting.
*/
object SortingDemo {
def main(arg:Array[String])={
val available_keys = List("id", "name",
"screen_name", "followers_count")
val (seed, key)=(arg(0),
if(arg.length<2) available_keys.head else arg(1))
if(!available_keys.exists(_==key)){
println("The key must be in "+available_keys+".")
exit(1)
}
/**
* Here is generating array data to be sorrted.
*/
val data:Array[Node] = genSampleData(seed)
def compareByKey(a:Node, b:Node):Int =
try{
// Compare as the integer value
(a \ key text).toInt.compare((b \ key text).toInt)
}
catch{
case e => (a \ key text).compare((b \ key text))
}
/**
* Sort 'data' by
* Sorting#quickSort[K <% Ordered[K]]quickSort(a:Array[K])
* , which is equivalent to
* Sorting#quickSort[K]quickSort(a:Array[K])
* (implicit view:(K)=>Ordered[K])
*/
{
implicit def view(node:Node)=new Ordered[Node]{
def compare(that:Node):Int=compareByKey(node, that)
}
Sorting.quickSort(data)
}
/**
* If K inherits Ordered[K], we don't have to provide the view.
* In this case, the compiler will implicitly choose 'Predef.identity' as it.
*/
{
class OrderedNode(val node:Node) extends Ordered[OrderedNode]{
def compare(that:OrderedNode):Int=
compareByKey(this.node, that.node)
}
data.map(new OrderedNode(_)) match {
case d => {
Sorting.quickSort(d)
System.arraycopy(d.map(_.node).asInstanceOf[Array[Node]], 0,
data, 0, data.length)
}
}
}
/**
* Sort 'data' by
* Sorting#stableSort[K](a:Array[K], f:(K, K)=>Boolean)
* This is really easy to use, and it should be usually used
* if K does not inherit Ordered[K].
*/
Sorting.stableSort(data, (a:Node, b:Node)=>compareByKey(a, b)<0)
data.foreach{d =>
println((d \ "screen_name" text)+": "+(d \ key text))
}
}
def genSampleData(screen_name:String):Array[Node] = {
import java.net.{URL, HttpURLConnection}
import scala.xml.XML
val following_url = "http://twitter.com/statuses/friends/%s.xml"
val url=following_url.replace("%s", screen_name)
def empty = Set.empty[Node]
def page(n:Int, set:Set[Node]):Set[Node] = {
var urlConn = new URL(url+"?page="+n).openConnection match {
case con:HttpURLConnection => {
con.connect();
con.getResponseCode match {
case 200 => { }
case _ => { }
}
con
}
}
(XML.load(urlConn.getInputStream) \\ "user").foldLeft(empty){
(m, user)=> m + user
}
match {
case _set if(_set.isEmpty) => set
case _set => page(n+1, set++_set);
}
}
page(1, empty).toArray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment