Last active
March 13, 2017 17:20
-
-
Save deyindra/6c444ffb3c88afe95a4f7f2b4e1e8f17 to your computer and use it in GitHub Desktop.
Custom Stream
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
import scala.annotation.tailrec | |
/** | |
* Created by i.dey on 3/12/17. | |
*/ | |
trait Stream[+T] { | |
def isEmpty : Boolean | |
def head : T | |
def tail : Stream[T] | |
@tailrec | |
final def apply(n:Int): T = { | |
if(isEmpty) | |
throw new NoSuchElementException | |
else if(n==0){ | |
head | |
}else{ | |
tail.apply(n-1) | |
} | |
} | |
} | |
object EmptyStream extends Stream[Nothing]{ | |
override def isEmpty: Boolean = true | |
override def head: Nothing = throw new NoSuchElementException | |
override def tail: Stream[Nothing] = throw new NoSuchElementException | |
} | |
class ConStream[T](hd:T, tl: => Stream[T]) extends Stream[T]{ | |
override def isEmpty: Boolean = false | |
override def head: T = hd | |
lazy val tail: Stream[T] = tl | |
} | |
object Stream{ | |
def apply[T](lo:T, high: T)(greater:(T,T)=>Boolean, f:(T)=>T):Stream[T] = { | |
if(greater(lo,high)){ | |
EmptyStream | |
}else{ | |
new ConStream[T](lo,apply(f(lo),high)(greater,f)) | |
} | |
} | |
def apply[T](stream:Stream[T])(p:(T)=>Boolean): Stream[T] ={ | |
if(stream.isEmpty) | |
EmptyStream | |
else | |
if(p(stream.head)) | |
new ConStream[T](stream.head, apply(stream.tail)(p)) | |
else | |
apply(stream.tail)(p) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment