Pass by Reference

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

I'm writing an application that has multiple digital filters. Calling the filter:

  • Calculates a filtered result, and
  • Updates the filter's history.

That is, two different things are being modified here - there's a result returned from the function call, and as a side-effect, a data structure gets updated.

My first approach was to write the filter as a namespace, and try to treat them like an object. Only.. namespaces aren't really objects, and things got ugly fast.

My second approach was to write something like:

function do_filter( sequence theFilter, atom theInput ) 
   atom theOutput = theFilter[2] * theFilter[1] * theInput 
   theFilter[2] = theFilter[1] 
   theFilter[1] = theInput 
 
   return theOutput 
end function 
 
atom theResult = do_filter( theFilter, theInput ) 

Of course, this doesn't work because Euphoria only passes parameters by value and not by reference. I started remembering why I'd worked on Py.

So what to do with the result of the filter?

One solution would be to pass a sequence back from the function, which is really clunky:

function do_filter( sequence theFilter, atom theInput ) 
   atom theOutput = theFilter[2] * theFilter[1] * theInput 
   theFilter[2] = theFilter[1] 
   theFilter[1] = theInput 
 
   return {theFilter, theOutput} 
end function 
 
sequence theResult = do_filter( theFilter, theInput ) 
theFilter = theResult[1] 
atom theOutput = theResult[2] 

Yes, it's the worst filter ever. I don't have the exact code in front of me, but it gets to the essence of the problem.

Another option is to store the value return inside theFilter, which is only slightly less clunky:

enum FILTER_HIST_1, FILTER_HIST_2, FILTER_RESULT 
 
function do_filter( sequence theFilter, atom theInput ) 
   atom theOutput = theFilter[FILTER_HIST_1] * theFilter[FILTER_HIST_2] * theInput 
   theFilter[FILTER_HIST_2] = theFilter[FILTER_HIST_1] 
   theFilter[FILTER_HIST_1] = theInput 
   theFilter[FILTER_RESULT] = theOutput 
 
   return theFilter 
end function 
 
-- pass the filter data and value to filter to the filtering routine 
theFilter = do_filter( theFilter, theInput ) 
 
-- save the filtered value 
atom result = theResult[FILTER_RESULT] 

But it raises the question: why do I have to jump through these hoops at all? Why can't OpenEuphoria let me pass values by reference like just about any other language?

- David

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

Search



Quick Links

User menu

Not signed in.

Misc Menu