"함수 reduce()"의 두 판 사이의 차이

 
(사용자 2명의 중간 판 17개는 보이지 않습니다)
1번째 줄: 1번째 줄:
;reduce


==JavaScript==
[[분류: JavaScript]]
{{참고|자바스크립트 배열 reduce()}}
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
</syntaxhighlight>
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(reducer));    // 130 = 100 + 20 + 10
console.log(numbers.reduce(reducer, 5)); // 135 = 5 + 100 + 20 + 10
</syntaxhighlight>
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10
</syntaxhighlight>
==PHP==
[[분류: PHP]]
{{참고|PHP array_reduce()}}
<syntaxhighlight lang='php' run>
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry += $i;
    return $carry;
});
echo $result; # 14
</syntaxhighlight>
<syntaxhighlight lang='php' run>
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry *= $i;
    return $carry;
}, 1);
echo $result; # 120
</syntaxhighlight>


==Python==
==Python==
[[category: Python]]
[[category: Python]]
;Python 3
{{참고|Python reduce()}}
<source lang='Python'>
<syntaxhighlight lang='Python' run>
import functools
from functools import reduce
print( functools.reduce(lambda x, y: x + y, numbers) )
a = [2, 3, 4, 5]
# 21
print( reduce((lambda x, y: x*y), a) ) # 120
</source>
</syntaxhighlight>


==같이 보기==
==같이 보기==
*[[map]]
*[[함수 map()]]
*[[filter]]
*[[함수 filter()]]
*[[lambda function]]
*[[lambda function]]
*[[맵리듀스 프로그래밍 모델]]

2021년 5월 3일 (월) 01:46 기준 최신판

reduce

1 JavaScript[ | ]

const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
const numbers = [100, 20, 10];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(reducer));    // 130 = 100 + 20 + 10
console.log(numbers.reduce(reducer, 5)); // 135 = 5 + 100 + 20 + 10
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10

2 PHP[ | ]

$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry += $i;
    return $carry;
});
echo $result; # 14
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry *= $i;
    return $carry;
}, 1);
echo $result; # 120

3 Python[ | ]

from functools import reduce
a = [2, 3, 4, 5]
print( reduce((lambda x, y: x*y), a) ) # 120

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}