Apply a callback to an array: Difference between revisions

Content added Content deleted
m (Added subject matter link, alphebetized, fixed formatting and style)
Line 1: Line 1:
{{task}}
{{task}}


Apply a callback function to each element of an Array
Apply a [[callback function]] to each element of an Array


==[[Ruby]]==
#create the array
ary = [1,2,3,4,5]
#create the function (print the square)
def print_square(i)
puts i**2
end
#ruby
ary.each do |i|
print_square(i)
end
# prints 1,4,9,16,25

# Alternatively:
[1,2,3,4,5].each { |i| puts i**2 }


==[[C++]]==
==[[C++]]==


Compiler: [[GNU Compiler Collection]] gcc/g++ version 4.1.1
'''Compiler:''' [[GNU Compiler Collection]] 4.1.1
Using c-style array
Using [[c-style array]]


#include <iostream> //cout for printing
#include <iostream> //cout for printing
Line 40: Line 25:
//prints 1 4 9 16 25
//prints 1 4 9 16 25


Using std::vector
Using [[std]]::[[std::vector|vector]]


#include <iostream> //cout for printing
#include <iostream> //cout for printing
Line 96: Line 81:
squares1 = [square(n) for n in numbers] # list comprehension
squares1 = [square(n) for n in numbers] # list comprehension
squares2 = map(square, numbers)
squares2 = map(square, numbers)

==[[Ruby]]==
#create the array
ary = [1,2,3,4,5]
#create the function (print the square)
def print_square(i)
puts i**2
end
#ruby
ary.each do |i|
print_square(i)
end
# prints 1,4,9,16,25
# Alternatively:
[1,2,3,4,5].each { |i| puts i**2 }