[Haskell-beginners] Re: scope for variables

Maciej Piechotka uzytkownik2 at gmail.com
Wed Dec 9 17:13:45 EST 2009

On Wed, 2009-12-09 at 22:40 +0100, legajid wrote:
> Hello,
> i wrote the following (very simplified) program :
> word :: [Char]
> word="initial"
> letters=['a'..'z']
> myloop = do
>   myloop2

word from topmost declaration (="initial") if it was used

> myloop2 = do
>   putStrLn word

word from topmost declaration (="initial")

>   putStrLn letters
> main = do
>        putStrLn "Enter the word"
>        word <- enter_word
word="abcdefghij" and is local variable/constant.
>        myloop 
> enter_word= do
>     return("abcdefghij")
> "word" is initially binded to the value "initial"
> myloop, calling myloop2, displays this value
> "Improving" my program, i add "main" that enters a new value for "word" 
> (here a fix one, ideally a getLine)
> To display this new value, i must call myloop with this parameter, which 
> is then passed to myloop2.
> Is there a way to make a "global binding ?", thus changing the value of 
> "word", so that i don't have to modify the code for myloop and myloop2 
> (now being passed a parameter), that worked fine. This would make the 
> program modular and easy to modify, without modifying all existing 
> functions. Or is it non-sense in Haskell ?

It is practically 'non-sense' and would make a program less modular. If
function depends on some value make it an argument.

Generally you should avoid IO as much as possible.

> Thanks,
> Didier.


PS. Actually it is possible to do it with global variables but:
1. It uses an extentions
2. You should know why in most cases it is not what you want
3. It requires some knoledge about compilation process as
'officially' (w/out extention) it is nondeterministic.

More information about the Beginners mailing list