Re: delegate support in euphoria?
- Posted by DerekParnell (admin) Apr 20, 2012
- 1495 views
hello, I'm a beginner, I would like to know if Euphoria supports the delegate concept, also known as: callbacks, anonymous functions.
for example, a 'retain' function filters a sequence based on a predicate (a func that returns a boolean). retain would take the sequence and the predicate as its two parameters.
now the programmer can use this construct, as an abstraction for later work that only differs by the arguments. (no need to write the same code when the "block" can be passed from outside)
Yes. The function routine_id() can be used to get an handle to any procedure or function and then that handle can be passed as an argument to a routine, which would call the handle's routine using either the call_func() or call_proc() as appropriate.
As an example, the custom_sort() function expects you to pass a routine_id as the comparison algorithm.
Here is an example of your 'retain' idea.
function odd_val(object X) if sequence(X) then return 0 end if if integer(X) then return and_bits(X,1) end if return 0 end function function multiple_3(object X) if sequence(X) then return 0 end if if integer(X) then return remainder(X, 3) = 0 end if return 0 end function function retain(sequence A, integer criteria) sequence temp integer p = 0 temp = repeat(0, length(A)) for i = 1 to length(A) do if call_func(criteria, {A[i]}) then p += 1 temp[p] = A[i] end if end for return temp[1.. p] end function sequence testdata = {1,2,3,4,5,6,7,8,9,10,11,12} ? retain(testdata, routine_id("odd_val")) --> {1,3,5,7,9,11} ? retain(testdata, routine_id("multiple_3")) --> {3,6,9,12}