1. RE: strong typing and error handling
Mike Nelson wrote:
>
>
> Until such time as Euphoria has pass-by-reference, there is a nasty
> workaround for types that will only be used for a few variables--its
> impractical for programs with hundereds of variables. Let's assume we
> want
> to have variables that will reject a sequence, but modify any atom to
> coerce
> its value to an integer between 1 and 10.
>
> -- this code needs to be written only once
> function coerce(object x)
> if atom(x) then
> x=floor(x)
> if x<min then x=1 end if
> if x>max then x=10 end if
> end if
> return x
> end function
>
> -- the code from here on is repeated for EACH variable
> integer SET_A
>
> type a_object(object x)
> object y
> y=coerce(x)
> if not equal(x,y) then call_proc(set_a,{y}) end if
> return integer(x)
> end type
>
> a_object a
>
> procedure set_a(object x)
> a=x
> end procedure
>
> SET_A=routine_id("set_a")
>
>
> This is a huge amount of overhead to simulate pass by reference, but it
> does
> work.
Of course, that basically boils down to calling coerce() for each
parameter, which you could do directly without use of types, although it
is a bit annoying. (I was actually thinking about asking for this
feature in Diamond for setting properties -- specifying an optional type
routine for properties that could accept/reject/modify the property
value upon setting it. But if you code it as a method, you can do it
yourself without any extra Diamond overhead.)
Another technique I use is to have a global variable (or local to the
whole file, anyway) for each type the I might want to "coerce" and use
that instead of the original value that is passed to a function. For
instance, if I want to send some bit-flags to a function, and they need
to be "or'ed" together if a send a sequence of them:
atom flags -- this will hold final flags value
type or_flags(object x)
if atom(x) then
-- no modifying needed, just copy
flags = x
else
flags = or_all(x) -- call routine to OR together flags
end if
return 1 -- always returns TRUE
end type
Now when I write my functions, I do this:
function some_function(object parameter, or_flags dummy)
-- "dummy" is a dummy variable, we use the global "flags"
-- instead inside the function which has the proper
-- modified (possibly) value.
... function stuff ...
end function
2. RE: strong typing and error handling
Oh, I should point out that this technique doesn't work prior to v2.4
when using the translator because the older versions don't call
user-defined types, but 2.4 does call them if it has a side-effect such
as this...
>
> Now when I write my functions, I do this:
>
> function some_function(object parameter, or_flags dummy)
>
> -- "dummy" is a dummy variable, we use the global "flags"
> -- instead inside the function which has the proper
> -- modified (possibly) value.
>
> ... function stuff ...
>
> end function
>