Skip to content
Snippets Groups Projects
Writers.scala 1.06 KiB
Newer Older
package readerwriter


import readerwriter.internal.Writer, Writer._
import util._


object Writers {
  /* everything required to use tell and the monad operations
   * is already imported */

  def collatzDepth(n: Int): Writer[List[String], Int] = ???

  def collatzSearch(start: Int, limit: Int): Writer[List[String], Int] = ???

}

object CollatzWithoutWriter {
  def collatzDepth(n: Int): (List[String], Int) =
    if (n == 1)
      (List("got 1, doing nothing"), 0)
    else if (n % 2 == 0) {
      val (way, depth) = collatzDepth(n / 2)
      (s"got $n, halving" :: way, depth + 1)
    } else {
      val (way, depth) = collatzDepth(n * 3 + 1)
      (s"got $n, tripling plus one" :: way, depth + 1)
    }

  def collatzSearch(start: Int, limit: Int): (List[String], Int) = {
    val (way, depth) = collatzDepth(start)
    if (depth < limit) {
      val (way2, number) = collatzSearch(start + 1, limit)
      (s"testing $start" :: way ++ (s"depth was $depth" :: way2), number)
    } else
      (s"testing $start" :: way ++ List(s"depth was $depth", s"returning $start"), start)
  }
}