Variable scopes #programming #haskell #perl #python
Variable scopes, helping programmers since the days of yore. Typos are easy to make:
$ cat fun.hs
main :: IO ()
main = do
mapM_ (\old_key -> print old_key) [1..5]
mapM_ (\new_key -> print old_key) [6..10]
Looks pretty innocent, right? But I missed something... can we get some help from the compiler, please?
$ ghc fun.hs
[1 of 1] Compiling Main ( fun.hs, fun.o )
fun.hs:4:28: error: Variable not in scope: old_key
|
4 | mapM_ (\new_key -> print old_key) [6..10]
| ^^^^^^^
Ah, yes, good point, thanks!
How about an interpreted language?
$ cat fun.pl
#!/usr/bin/perl
use v5.12;
foreach my $old_key (1, 2, 3, 4, 5) {
say $old_key;
}
foreach my $new_key (6, 7, 8, 9, 10) {
say $old_key;
}
I made the same mistake again, silly me! Does the interpreter help?
$ perl fun.pl
Global symbol "$old_key" requires explicit package name (did you forget to declare "my $old_key"?) at fun.pl line 10.
Execution of fun.pl aborted due to compilation errors.
Thanks!
Let's try another language often recommended to beginners and students alike:
$ cat fun.py
#!/usr/bin/python3
for old_key in [1, 2, 3, 4, 5]:
print(old_key)
for new_key in [6, 7, 8, 9, 10]:
print(old_key)
Oops, I did it again! Hopefully the interpreter to the rescue:
$ python3 fun.py
1
2
3
4
5
5
5
5
5
5
Oh no.
Add comment
To avoid spam many websites make you fill out a CAPTCHA, or log in via an account at a corporation such as Twitter, Facebook, Google or even Microsoft GitHub.
I have chosen to use a more old school method of spam prevention.
To post a comment here, you need to:
- Configure a newsreaderยน to connect to the server
- Open the newsgroup called
ยน Such as Thunderbird, Pan, slrn, tin or Gnus (part of Emacs).koldfront.dk
on port1119
using nntps (nntp over TLS).lantern.koldfront
and post a follow up to the article.Or, you can fill in this form: