2016-10-22 2 views
3

0부터 n까지의 숫자를 더하는 함수를 작성하고 싶습니다. (이상적으로 이것은 모든 숫자에 대해 일반적인 것이지만 i32으로 해결할 것입니다).녹에서 숫자의 범위를 어떻게 합산 할 수 있습니까?

src/lib.rs:5:18: 5:22 error: no method named `fold` found for type `[std::ops::Range<i32>; 1]` in the current scope 
src/lib.rs:5   [0 .. n].fold(0, |a, b| a + b) 
           ^~~~ 
src/lib.rs:5:18: 5:22 note: the method `fold` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator` 

나는 또한 sum()와 함께이 시도했습니다 :

mod squares { 

    pub fn sum_from_zero(n: i32) -> i32 { 
     [0 .. n].sum() 
    } 
} 

#[test] 
fn test_sum_from_zero() { 
    assert_eq!(15, squares::sum_from_zero(5)); 
} 

그리고 다음과 같은 컴파일러 오류 가지고 :

src/lib.rs:5:18: 5:21 error: no method named `sum` found for type `[std::ops::Range<i32>; 1]` in the current scope 
src/lib.rs:5   [0 .. n].sum() 
           ^~~ 
src/lib.rs:5:18: 5:21 note: the method `sum` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator` 
src/lib.rs:5:18: 5:21 error: no method named `sum` found for type `[std::ops::Range<i32>; 1]` in the current scope 
src/lib.rs:5   [0 .. n].sum() 
           ^~~ 
src/lib.rs:5:18: 5:21 note: the method `sum` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator` 

mod squares { 

    pub fn sum_from_zero(n: i32) -> i32 { 
     [0 .. n].fold(0, |a, b| a + b) 
    } 
} 

#[test] 
fn test_sum_from_zero() { 
    assert_eq!(15, squares::sum_from_zero(5)); 
} 

나는 다음과 같은 컴파일러 오류

내가해야합니까? 명시적인 범위/특성을 선언 하시겠습니까?

+1

당신은'범위 '유형의 단일 요소의 배열로 만드는 (일명'[표준 : 작전 :: 범위 을 1]'). 아마도 연산자 우선 순위를 변경하여'n '에'sum()'을 호출하지 않는'(0 .. n)'을 의미 할 것입니다. ([Playground Example] (https://play.rust-lang.org/?gist=b27932d99482f3ddd62697b62f1fe28c&version=stable&backtrace=0) – Aurora0001

답변

9

문제는 범위 배열 (대괄호)을 만드는 것이지만 범위 (접기가 정의 된)를 원한다는 것입니다.

또 다른 것은 범위 구문 (..)은 하한값만을 포함한다는 것입니다. 상한선은 제외되므로 원하는 결과를 얻으려면 n+1까지 반복해야합니다.

mod squares { 

    pub fn sum_from_zero(n: i32) -> i32 { 
     (0 .. n+1).fold(0, |a, b| a + b) 
    } 
} 

#[test] 
fn test_sum_from_zero() { 
    assert_eq!(15, squares::sum_from_zero(5)); 
} 
+1

@ Aurora0001 예, 정확합니다. – Arjan

+2

녹 1.11에서 '반복자'특성에는 'sum' 메서드와 범위는 반복자이므로'fold '할 필요가 없습니다. 또한, n × (n + 1)/2의 언급은 없다. – mcarton

+0

@mcarton hea는 그의 예제에서 이미'sum'을 사용했습니다. – Arjan

관련 문제