Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of IO defined variables

Tags:

haskell

I've discovered that when doing IO in Haskell, variables that are assigned using the <- operator are only in scope for the statements immediately after them - not in where clauses.

For example:

main :: IO()
main =  do
          s <- getLine
          putStr magic
            where
              magic = doMagic s

This won't work as s is not in scope. I did some research to confirm it and found this article:

Unlike a let expression where variables are scoped over all definitions, the variables defined by <- are only in scope in the following statements.

So how can I make s available for use in the where clause?

like image 248
Nick Brunt Avatar asked Feb 22 '23 16:02

Nick Brunt


1 Answers

In addition to the general let form, there's a special let form for use with do syntax you can use instead:

main :: IO()
main =  do
          s <- getLine
          let magic = doMagic s
          putStr magic

magic is available in all following lines in the block.

like image 60
dave4420 Avatar answered Mar 03 '23 12:03

dave4420