start
とend
の間の各番号に繰り返しpub fn verse(num: i32) -> String
を繰り返し呼び出した結果の連結文字列を返すpub fn sing(start: i32, end: i32) -> String
を作成しようとしています。逆方向範囲を反復処理するにはどうすればよいですか?
:
私のコード:
pub fn verse(num: i32) -> String {
match num {
0 => "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n".to_string(),
2 => "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n".to_string(),
num => format!("{0} bottles of beer on the wall, {0} bottles of beer.\nTake one down and pass it around, {1} bottles of beer on the wall.\n",num,(num-1)),
}
}
pub fn sing(start: i32, end: i32) -> String {
(start..end).fold(String::new(), |ans, x| ans+&verse(x))
}
問題を
#[test]
fn test_song_8_6() {
assert_eq!(beer::sing(8, 6), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and pass it around, 5 bottles of beer on the wall.\n");
}
が""
を返すbeer::sing(8,6)
で失敗していることです。
ありがとうございます。レンジは前方のみを反復するのはなぜですか? –
@CalebJasik:それは実際にはそれが前進を繰り返すだけではなく、典型的な半開きの範囲をモデル化する以上のものです。この意味で、 'start == end'は空の範囲を表し、' start> = end'はバグです。また、Rangeコードをよりシンプルに(したがって高速に)作成します。逆の反復では、 'rev'を明示的に呼び出すと、完了です。 –