Python has Traps; Does Euphoria have Programming Traps?
- Posted by _tom (admin) Aug 13, 2013
- 2370 views
A programmming trap is a "syntax feature that can create a subtle hard to find bug."
I have identified programming traps in Python, but I do not know of any in Euphoria.
Do you know of a programming trap in Euphoria that everyone should be informed about and should be documented?
Here are the details of what I mean:
Explaining a programming trap to a novice programmer would be an unpleasant challenge and a programming trap makes documenting a language harder. A language designed to teach programming should not have any programming traps. Languages for serious programming should not have programming traps either.
Python has programming traps:
- Python Alias Trap.
- Python Scope Trap.
- Python Parameter Trap.
Remember that Python was explicitly designed to teach programming. (ABC was designed first, so this is the second generation teaching language by the same author.)
Python Alias Trap.
Python variables can be aliased.
Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = [1,2,3] >>> b = a >>> b is a True >>> b[0] = 17 >>> print a [17, 2, 3] >>> # SURPRISE!
Aliasing is "when you make a change to a variable and that change appears in another variable."
Euphoria objects do not suffer from aliasing.
sequence a = {1,2,3} sequence b b = a -- 'b' is a distinct object from 'a' b[1] = 17 ? b -- {17,2,3} -- as expected ? a -- {1,2,3} -- as expected
Python Scope Trap
The Python example shows what happens when variables are automagically created by just typing an identifier.
# Python Example name = 'Jack' def say_hello(): print('Hello ' + name + '!') def change_name(new_name): name = new_name say_hello() # Hello Jack! change_name( "Piper" ) say_hello() # SURPRISE # Hello Jack!
In the Python say_hello() the variable name is not the same as the previously declared variable. There is no warning that a new, local, variable is created. As a result you get a surprise.
-- Euphoria Example sequence name = "Jack" procedure say_hello() puts(1, "Hello " & name & "!\n" ) end procedure procedure change_name( sequence new_name ) name = new_name end procedure say_hello() -- Hello Jack! change_name( "Piper" ) say_hello() -- Hello Piper!
In the Euphoria say_hello() the variable name is the same as the previously declared variable. No surprises.
Python Parameter Trap
In Python the expression for a default parameter is evaluated just once.
y = 3 def foo( x = y*y ): return x print( foo(3) ) # 3 print( foo() ) # 9 y = 8 print( foo() ) # SURPRISE! # 9
In Euphoria the expression for a default parameter is recalculated as expected.
atom y ? foo(3) -- 3 y = 3 ? foo() -- 9 y = 8 ? foo() -- 64 function foo( atom x = y*y ) return x end function