Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 82 lines (56 sloc) 1.047 kb
6f63c90f »
2011-11-21 From around my laptop
1 Problem: we have a list of numbers we want to triple (multiply by 3)
2
3 Math:
4
5 f(x) = 3x
6
7 C:
8
9 int i;
10 for (i = 0; i < sizeof(a) / sizeof(a[0]); i++) {
11 printf("%d\n", a[i]);
12 }
13
14 Java:
15
16 // traditional
17 for (int i = 0; i < array.length; i++) {
18 triple(array[i]);
19 }
20
21 // iterator
22 Iterator<Item> i = collection.iterator();
23 while (i.hasNext()) {
24 triple(collection.get(i));
25 }
26
27 // iterator shorthand
28 for (Item item : array) {
29 triple(item);
30 }
31
32 Perl:
33
34 foreach (@array) {
35 triple($_);
36 }
37
38 PHP:
39
40 foreach ($array as $item) {
41 triple($item);
42 }
43
44 Python:
45
46 for item in array:
47 triple(item)
48
49 JavaScript:
50
51 for (i in array) {
52 triple(array[i]);
53 }
54
55 // or if your browser/framework has defined it:
56 array.each(triple);
57 // or
58 array.map(triple);
59 // among other things...
60
61 SML/NJ:
62
63 (* There aren't loops in SML/NJ, just recursion. *)
64 fun triple [] = []
65 | triple (h :: t) = h * 3 :: triple (t);
66
67 Ruby:
68
69 for item in array
70 triple(item)
71 end
72
73 array.each do |item|
74 triple(item)
75 end
76
77 array.each { |i| triple(i) }
78 array.each(&method(:triple))
79
80 array.each { |i| i * 3 }
81
Something went wrong with that request. Please try again.