Skip to content
Snippets Groups Projects
Writers.scala 1.05 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 then
      (List("got 1, doing nothing"), 0)
    else if n % 2 == 0 then
      val (way, depth) = collatzDepth(n / 2)
      (s"got $n, halving" :: way, depth + 1)
      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 then
      val (way2, number) = collatzSearch(start + 1, limit)
      (s"testing $start" :: way ++ (s"depth was $depth" :: way2), number)
      (s"testing $start" :: way ++ List(s"depth was $depth", s"returning $start"), start)