Pastey Exercism Tutorial: Accumulate

-- accumulate
 
sequence s1 = {1,2,3,4,5} 
 
 
-- on each item square the value 
 
? "Euphoria like" 
? s1*s1 
 
------------------------------------------------------------------------ 
/* 

? "more Phix like" 
? sq_mul( s1, s1 ) 
*/ 
 
------------------------------------------------------------------------ 
? "the long way" 
-- you could square each item individually 
 
sequence s2 = {1,2,3,4,5} 
for i=1 to length(s2) do 
    s2[i] = s2[i] * s2[i] 
end for 
? s2 
 
/* 

Implement the `accumulate` operation, which, given a collection and an 
operation to perform on each element of the collection, returns a new 
collection containing the result of applying that operation to each element of 
the input collection. 
 
Given the collection of numbers: 
 
- 1, 2, 3, 4, 5 
 
And the operation: 
 
- square a number (`x => x * x`) 
 
Your code should be able to produce the collection of squares: 
 
- 1, 4, 9, 16, 25 
*/ 

1. Comment by petelomax Oct 01, 2019

Another approach:

function apply(sequence s, integer rid) 
    for i=1 to length(s) do 
        s[i] = call_func(rid,{s[i]}) 
    end for 
    return s 
end function 
 
function square(atom a) 
    return a*a 
end function 
constant r_square = routine_id("square") 
 
?apply({1,2,3,4,5},r_square)    -- {1,4,9,16,25}