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 : 실제로는 앞으로 만 반복되는 것이 아니라 일반적인 half-open 범위를 모델링하는 것 이상입니다. 이런 의미에서'start == end'는 빈 범위를 나타내며'start> = end' 버그를 나타냅니다. 또한 Range 코드를 더 간단하게 만듭니다. 역방향 반복의 경우,'rev'를 명시 적으로 호출하면 완료됩니다. –