Skip to content

Instantly share code, notes, and snippets.

@folone
Last active December 16, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save folone/5445048 to your computer and use it in GitHub Desktop.
Save folone/5445048 to your computer and use it in GitHub Desktop.
IO monad stack overflow
> effect/console
[warn] Credentials file /home/folone/.ivy2/.credentials does not exist
[warn] Credentials file /home/folone/.ivy2/.credentials does not exist
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.9.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scalaz._, Scalaz._, effect._
import scalaz._
import Scalaz._
import effect._
scala> val monadic = (1 to 30000).toList.map(IO(_)).reduceLeft{ (a, b) => for (i <- a; j <- b) yield i + j }
monadic: scalaz.effect.IO[Int] = scalaz.effect.IOFunctions$$anon$5@5d5fe2c0
scala> val applicative = (1 to 30000).toList.map(IO(_)).reduceLeft{ (a, b) => (a |@| b){_ + _} }
applicative: scalaz.effect.IO[Int] = scalaz.effect.IOFunctions$$anon$5@4b766360
scala> applicative.unsafePerformIO
res0: Int = 450015000
scala> monadic.unsafePerformIO
java.lang.StackOverflowError
at scalaz.effect.IOFunctions$$anon$5.apply(IO.scala:222)
at scalaz.effect.IO$$anonfun$flatMap$1.apply(IO.scala:62)
at scalaz.effect.IO$$anonfun$flatMap$1.apply(IO.scala:61)

As described by @runarorama, any Monad can be trampolined as long as it has a transformer. Unfortunately, there's no transformer for IO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment