Advertisement
Guest User

Untitled

a guest
Jun 8th, 2014
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.90 KB | None | 0 0
  1. class Ls [T](hd : Option[T], tl : Ls[T]){
  2.     def head : Option[T] = hd
  3.     def tail : Ls[T] = tl;
  4.     def foldr[ACC](acc: ACC,fun:(ACC,Option[T])=>ACC):ACC = {
  5.         hd match {
  6.             case None => acc
  7.             case Some(x) => tl.foldr(fun(acc,Some(x)),fun)
  8.         }
  9.     }
  10.     def concat(x: T):Ls[T] = {
  11.         new Ls[T](Some(x),this)
  12.     }
  13.     override def clone() = {
  14.         this.foldr[Ls[T]](new Ls[T](None,null),(acc: Ls[T],x:Option[T]) => x match{
  15.             case None => acc
  16.             case Some(y) => acc.concat(y)
  17.         })
  18.     }
  19.     def len():Int = {
  20.         foldr[Int](0,(acc: Int,x:Option[T]) =>
  21.             x match{
  22.                 case None => acc
  23.                 case Some(y) => acc+1
  24.             }
  25.         )
  26.     }
  27. };
  28. object LsOp{
  29.     def subl[T](src : Ls[T], start : Int, end : Int):Option[Ls[T]] = {
  30.         if((start<end) && (end < src.len()-1))
  31.             __subl[T](start,end,0,new Ls[T](None,null),src)
  32.         else
  33.             None
  34.     }
  35.     private[this] def __subl[T](start : Int, end : Int, count : Int, acc : Ls[T], ls : Ls[T]):Option[Ls[T]] = {
  36.         ls.head match {
  37.             case None => None
  38.             case Some(x) =>
  39.                 if(count < start){
  40.                     __subl[T](start,end,count+1,acc,ls.tail)
  41.                 }else if((count<=end)&&(count >=start)){
  42.                     __subl[T](start,end,count+1,acc.concat(x),ls.tail)
  43.                 }else{
  44.                     Some(acc)
  45.                 }
  46.         }
  47.     }
  48.     def optionListToStr[T](ls : Option[Ls[T]]):String = {
  49.         ls match{
  50.             case None => "an error occured while performing a list operation"
  51.             case Some(x) => listToStr(x)
  52.         }
  53.     }
  54.     def listToStr[T](ls: Ls[T]):String = {
  55.         val str = __listToStr(ls,"")
  56.         str.substring(0,str.length-1)
  57.     }
  58.     private[this] def __listToStr[T](ls : Ls[T],acc: String):String = {
  59.         ls.head match{
  60.             case None => acc
  61.             case Some(x) => __listToStr[T](ls.tail,x+","+acc)
  62.         }
  63.     }
  64. };
  65.  
  66.  
  67. object Main extends App{
  68.     println("test")
  69.     val ls = new Ls[Int](Some(1),new Ls[Int](Some(2),new Ls[Int](Some(26),new Ls[Int](Some(32),new Ls[Int](None,null)))))
  70.     println(ls.concat(1).clone().len())
  71.     println(LsOp.optionListToStr(LsOp.subl(ls,0,2)));
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement