Without much discussion, here is some source code for a Scalaz 7 “Hello, world” example, using the Scalaz putStrLn
function:
package scalaz_tests import scalaz._ import effect._ import IO._ /** * from http://eed3si9n.com/learning-scalaz/IO+Monad.html * requires these in build.sbt: * * libraryDependencies ++= Seq( * "org.scalaz" %% "scalaz-core" % "7.1.3", * "org.scalaz" %% "scalaz-effect" % "7.1.3" * ) * */ object ScalazHelloWorld extends App { val action1 = for { _ <- putStrLn("Hello, world!") } yield () //println("me first") action1.unsafePerformIO }
Regarding the source code, note that no printing happens until the unsafePerformIO
function is called. That’s why I put the other println
statement in there before that line. If you un-comment the println
statement, you’ll see that it is printed first. Or, if you remove the unsafePerformIO
function call, you’ll see that there is no output.
I left all the extra import
statements in there because I want to see/know/remember where things like the putStrLn
function come from. (It looks like putStrLn
is defined as scalaz.effect.IO.putStrln in Scalaz 7.)
Note the comment about the Scala/SBT build.sbt file. You specifically need to import the scalaz-effect library for this example to work. (I assume that you need the core library as well, but I know that it won’t work without scalaz-effect.)
A second Scalaz putStrLn example
Okay, while I’m in the neighborhood, here’s a second Scalaz putStrLn
example that also uses readLn
:
object ScalazTest2 extends App { val whoAreYou = for { _ <- putStrLn("who are you?") name <- readLn _ <- putStrLn("hello " + name) } yield () whoAreYou.unsafePerformIO }
That example comes from this page.
(If you know Haskell, you know that this for
loop looks like a Haskell do
loop.)