Skip to content
irxground edited this page Sep 9, 2013 · 6 revisions

各言語における for および foreach を比較する。

C

int i;
for (i = 0; i < SIZE; i++) {
    sum += i;
}
for (Item *item = list; item != NULL; item++) {
    sum += p->value;
}

C++

誰か書いて

Java

for (int i = 0; i < list.length; i++) {
    sum += list[i];
}
for (Item item : list) {
    sum += item.value
}

C#

foreach (var item in list) {
    sum += item.Value;
}

use reduce

sum += list.Aggrigate(0, item => sum + item.Value)

Ruby

# 推奨されない
for i in 0 ... MAX
  sum += i
end
# better
(0...MAX).each do |i|; end
MAX.times do |i|; end
list.each do |item|
  sum += item.value
end
sum += list.inject(0){ |sum, item| sum + item.value }

PHP

foreach($list as $item) {
    $sum += $item->value
}

Haskell

sum = sumList' 0 list
        where
          sumList' sum []     = sum
          sumList' sum (x:xs) = sumList' (sum + value x) xs

Fortran

integer i, sum
sum = 0
DO i = 1, 10
  sum = sum + i
END DO

Basic

FOR i = 1 TO 10
  sum = sum + i
NEXT i

_sidebar

Clone this wiki locally