Last active
August 29, 2015 14:04
-
-
Save vmarquez/9888f3c55a2f18f3f2b3 to your computer and use it in GitHub Desktop.
Trampoline overflow
This file contains 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 scalaz._ | |
import Scalaz._ | |
import scalaz.Free._ | |
//calling a.run(0) blows up obviously due to stack issues | |
val a = (0 to 10000).map(ii => State[Int,Int](i => (i,ii)) ).foldLeft( State[Int,Int](i => (i,0)) )( (s,a) => s.flatMap(i => a.map(ii => (ii+i) ))) | |
//calling b.run(0) blows up, not stack safe. | |
val b = (0 to 10000).map(ii => StateT[Free.Trampoline,Int,Int](i => Trampoline.done((i,ii))) ).foldLeft( StateT[Free.Trampoline, Int,Int](i => Trampoline.done((i,0))) )( (s,a) => s.flatMap(i => a.map(ii => (ii+i) ))) | |
//this is one way to ensure stack safety by using liftF to go from a State[A,B] to a Free[a[State[A,a],B] | |
val c = (0 to 10000).map(ii => State[Int,Int](i => (i,ii)).liftF ).foldLeft( State[Int,Int](i => (i,0)).liftF )( (s,a) => s.flatMap(i => a.map(ii => (ii+i) ))) | |
//instead of run we'll foldRun | |
c.foldRun(0)( (a,b) => b(a)) | |
//Scalazzi, are there other ways? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment