I was looking through this code on Github, which was shared at the 2014 Lambda Conference in Boulder, Colorado this summer, and ran across this for
comprehension:
def gameLoop: IO[Unit] = for { input <- getLine _ <- putStrLn("So, you want to " + input + ", do you?") _ <- if (input == "quit") IO(Unit) else gameLoop } yield Unit
The use of the underscore in the for
comprehension (or for
loop) is what I thought was interesting. As the author states in his README file, “The underscore in the notation _ <- putStrLn(...)
just means we don’t care about the value of Unit
that will be produced by putStrLn
.”
If it helps to know what’s going on here, as the name implies, this gameLoop
is the main loop for a simple RPG game the author was creating at the Lambda Conference. Because putStrLn
returns Unit
, and because we don’t care about the IO(Unit)
potentially returned by the third line in the for
comprehension, the underscore is used on the left side of the statements/expressions.