Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Ls [T](hd : Option[T], tl : Ls[T]){
- def head : Option[T] = hd
- def tail : Ls[T] = tl;
- def foldr[ACC](acc: ACC,fun:(ACC,Option[T])=>ACC):ACC = {
- hd match {
- case None => acc
- case Some(x) => tl.foldr(fun(acc,Some(x)),fun)
- }
- }
- def concat(x: T):Ls[T] = {
- new Ls[T](Some(x),this)
- }
- override def clone() = {
- this.foldr[Ls[T]](new Ls[T](None,null),(acc: Ls[T],x:Option[T]) => x match{
- case None => acc
- case Some(y) => acc.concat(y)
- })
- }
- def len():Int = {
- foldr[Int](0,(acc: Int,x:Option[T]) =>
- x match{
- case None => acc
- case Some(y) => acc+1
- }
- )
- }
- };
- object LsOp{
- def subl[T](src : Ls[T], start : Int, end : Int):Option[Ls[T]] = {
- if((start<end) && (end < src.len()-1))
- __subl[T](start,end,0,new Ls[T](None,null),src)
- else
- None
- }
- private[this] def __subl[T](start : Int, end : Int, count : Int, acc : Ls[T], ls : Ls[T]):Option[Ls[T]] = {
- ls.head match {
- case None => None
- case Some(x) =>
- if(count < start){
- __subl[T](start,end,count+1,acc,ls.tail)
- }else if((count<=end)&&(count >=start)){
- __subl[T](start,end,count+1,acc.concat(x),ls.tail)
- }else{
- Some(acc)
- }
- }
- }
- def optionListToStr[T](ls : Option[Ls[T]]):String = {
- ls match{
- case None => "an error occured while performing a list operation"
- case Some(x) => listToStr(x)
- }
- }
- def listToStr[T](ls: Ls[T]):String = {
- val str = __listToStr(ls,"")
- str.substring(0,str.length-1)
- }
- private[this] def __listToStr[T](ls : Ls[T],acc: String):String = {
- ls.head match{
- case None => acc
- case Some(x) => __listToStr[T](ls.tail,x+","+acc)
- }
- }
- };
- object Main extends App{
- println("test")
- 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)))))
- println(ls.concat(1).clone().len())
- println(LsOp.optionListToStr(LsOp.subl(ls,0,2)));
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement