2016-10-22 9 views
3

ゼロからnまでの数値を合計する関数を記述したいと思います。 (理想的には、これはすべての数字に対して一般的ですが、私はi32のために解決します)。どのようにしてRustの数値の範囲を合計できますか?

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

あなたは 'レンジ'タイプ(別名 '[STD :: OPS ::レンジ; 1]')の単一要素の配列を作成しています。おそらく '(0 .. n)'を意味するだけで、演算子の優先順位を変更して、 'n 'に' sum() 'を呼び出さないようにするだけです。 ([Playground Example](https://play.rust-lang.org/?gist=b27932d99482f3ddd62697b62f1fe28c&version=stable&backtrace=0) – Aurora0001

答えて

9

問題は、範囲の配列(角括弧)を作成しているにもかかわらず、範囲(折り畳みが定義されている)が必要だったということです。

もう1つのことは、範囲構文(..)には下限のみが含まれていることです。これは上限を除いているので、希望の結果を得るには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から、Iterator特性には'sum'メソッドと範囲はイテレータなので、' fold'する必要はありません。また、n×(n + 1)/ 2の記載はない。 – mcarton

+0

@mcarton heaは彼の例で既に 'sum'を使用しています – Arjan