=?utf-8?B?UkU6IGVub3VnaCBjaGF0dGVy?=

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

Jason Gade wrote:

>I actually have written some (simple) code.  In fact, here is my
>version of a recursive sum function:
>
>-- Sum.e
>
>-- Ver 1.1
>-- November 1999
>
>-- Function to (recursively) add all of the elements
>-- of a sequence together
>
>-- Usage: a = Sum ( s )
>-- Returns the sum of all elements of s.
>
>global function Sum( sequence values )
>
>    integer list_length
>    atom total
>    object list_element
>
>    total = 0
>    list_length = length( values )
>
>    for i = 1 to list_length do
>
> list_element = values[i]
> if sequence( list_element ) then
>
>     total += Sum( list_element )
>
> else
>
>     total += list_element
>
> end if
>
>    end for
>
>    return total
>
>end function -- Sum
>
>Is there a better solution?


If by "better" you mean "more efficient," then yes, if only slightly:

global function sum(sequence values)
atom total
object list_element

   total = 0
   for i = 1 to length(values) do
      list_element = values[i]
      if sequence(list_element) then
         total += sum(list_element)
      else
         total += list_element
      end if
   end for

   return total
end function

If the length of a sequence is used only once in a given routine, you don't
need to define a separate variable for it -- just use it at the one point
it's needed. This saves you the CPU time it takes to allocate another
variable and assign the length value to it. In a recursive function like
this, the time saved can add up pretty fast.


Hep yadda,
Gabriel Boehme

----------
The way we describe our world shows how we think of our world.
How we think of our world governs how we interpret our world.
How we interpret our world directs how we participate in it.
How we participate in the world shapes the world.

Robert Fripp
----------

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

Search



Quick Links

User menu

Not signed in.

Misc Menu