Re: Proposal for 'math.e' (2007-08-07)

new topic     » goto parent     » topic index » view thread      » older message » newer message

Hello all,

I'd like to suggest to change the sum() function in the future 'math.e'
standard include file. The current proposal is:
global function sum (sequence list)
   -- Return the sum of all elements in 'list'.
   atom ret

   ret = 0
   for i = 1 to length(list) do
      ret += list[i]Rob's opinion: 
   end for
   return ret
end function

That means, 'list' currently can only contain atoms.

But it can also be useful to calculate the sum of several sequences
(taking advantage of Euphoria's built-in sequence operations).
Say we have 3 points, given by their x- and y-coordinates, and we want
to get the center of gravity of these points:
object A, B, C, G

A = {-2, 1}
B = { 5, 0}
C = { 0, 5}

G = sum({A,B,C}) / 3    -- calculate center of gravity
? G                     -- prints {1,2}; Cool, no? smile

IMHO there is a problem with this suggestion, though.
If by accident one of the variables is an atom, say
   C = 7
then the program will not crash, but the sum() function will return
a result that is probably not intended. In order to avoid such a silent
bug, my proposal is to use an appropriate type-check for the parameter
of sum(). So my new proposal is:
type sequence_of_a_xor_s (object x)
   -- A sequence whose top-level elements are either only atoms or only
   -- sequences (or which is empty).
   integer object_type

   if atom(x) then
      return 0
   end if

   if length(x) = 0 then
      return 1
   end if

   object_type = atom(x[1])
   for i = 2 to length(x) do
      if object_type != atom(x[i]) then
         return 0
      end if
   end for
   
   return 1
end type

global function sum (sequence_of_a_xor_s list)
   -- Return the sum of all elements in 'list'.
   -- Note: This does not do a recursive sum of sub-sequences.
   object ret

   if length(list) = 0 then
      return 0
   end if

   ret = list[1]
   for i = 2 to length(list) do
      ret += list[i]
   end for
   return ret
end function

Regards,
   Juergen

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu