Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Dec 25th, 2013  |  syntax: Scala  |  size: 1.16 KB  |  views: 42  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import scala.language.higherKinds
  2. import scalaz._
  3. import Scalaz._
  4. import iteratee._
  5. import iteratee.Input._
  6. import iteratee.Iteratee._
  7. import scalaz.std.iterable._
  8.  
  9. object Run extends App {
  10.   // sample using State monad
  11.  
  12.   def sampleI[A](k: Int): Iteratee[A, Vector[A]] =
  13.     sampleI[A](k, 0, Vector())
  14.  
  15.   private def sampleI[A](k: Int, n: Int, sample: Vector[A]):
  16.                   Iteratee[A, Vector[A]] =
  17.     cont[A, Id, Vector[A]]((c: Input[A]) => c match {
  18.         case Element(x) =>
  19.           sampleI(k, n + 1, algorithmR(k, n + 1, sample, x))
  20.         case _          =>
  21.           done(sample, Empty[A])
  22.       })
  23.  
  24.   val rand = new scala.util.Random()
  25.  
  26.   def algorithmR[A](k: Int, n: Int, sample: Vector[A], x: A): Vector[A] = {
  27.     if (sample.size < k) {
  28.       sample :+ x // must keep first k elements
  29.     } else {
  30.       val r = rand.nextInt(n) + 1 // for simplicity, rand is global/stateful
  31.       if (r <= k)
  32.         sample.updated(r - 1, x) // sample is 0-index
  33.       else
  34.         sample
  35.     }
  36.   }
  37.  
  38.   {
  39.     print((sampleI(10) &=
  40.            EnumeratorT.enumStream((Short.MinValue to Short.MaxValue).toStream)
  41.           ).run)
  42.   }
  43. }
clone this paste RAW Paste Data