Portal/Notes πŸ“
RustRustlings_exercise

Iterators

Versi Bahasa Indonesia. Baca dalam Bahasa Inggris

  • Pola iterator memungkinkan kamu melakukan tugas pada urutan item secara bergantian.
  • Iterator menyediakan cara untuk melintasi, mentransformasi, atau mengonsumsi elemen secara efisien tanpa perlu mengelola index atau loop secara manual.
  • Iterator Rust bersifat lazy secara default, artinya mereka tidak melakukan operasi sampai secara eksplisit digunakan (consumed).
  • collect() dapat mengambil apa pun yang iterable, dan mengubahnya menjadi koleksi yang relevan.
  • Referensi:

iterators1.rs

// When performing operations on elements within a collection, iterators are
// essential. This module helps you get familiar with the structure of using an
// iterator and how to go through elements within an iterable collection.

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    #[test]
    fn iterators() {
        let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"];

        // Create an iterator over the array.
        let mut fav_fruits_iterator = my_fav_fruits.iter();

        assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
        assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // Replace `todo!()`
        assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
        assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // Replace `todo!()`
        assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
        assert_eq!(fav_fruits_iterator.next(), None); // Replace `todo!()`
    }
}
  • Latihan ini sederhana, kita hanya perlu membuat iterator berdasarkan array my_fav_fruits.

  • Kita dapat melakukannya dengan memanggil method iter seperti ini:

    let mut fav_fruits_iterator = my_fav_fruits.iter();

iterators2.rs

// In this exercise, you'll learn some of the unique advantages that iterators
// can offer.

// Complete the `capitalize_first` function.
// "hello" -> "Hello"
fn capitalize_first(input: &str) -> String {
    let mut chars = input.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()),
    }
}

// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
    words.iter().map(|w| capitalize_first(w)).collect()
}

// Apply the `capitalize_first` function again to a slice of string
// slices. Return a single string.
// ["hello", " ", "world"] -> "Hello World"
fn capitalize_words_string(words: &[&str]) -> String {
    words.iter().map(|w| capitalize_first(w)).collect()
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_success() {
        assert_eq!(capitalize_first("hello"), "Hello");
    }

    #[test]
    fn test_empty() {
        assert_eq!(capitalize_first(""), "");
    }

    #[test]
    fn test_iterate_string_vec() {
        let words = vec!["hello", "world"];
        assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]);
    }

    #[test]
    fn test_iterate_into_string() {
        let words = vec!["hello", " ", "world"];
        assert_eq!(capitalize_words_string(&words), "Hello World");
    }
}
  • Tugas pertama di latihan ini adalah melengkapi fungsi capitalize_first.

    • Kita sudah memiliki sintaks match untuk char pertama dari input yang diberikan.

    • Kita hanya perlu menjadikannya huruf besar dan menggabungkannya dengan sisa karakter.

    • Kita dapat melakukannya dengan menggunakan format atau + seperti ini:

      format!("{}{}", first.to_uppercase(), chars.as_str())

      atau

      first.to_uppercase().to_string() + chars.as_str()
  • Tugas kedua dan ketiga agak mirip, di sini kita akan mempelajari betapa powerfulnya method collect.

  • Di fungsi capitalize_words_vector kita perlu melakukan iterasi pada words yang diberikan dan mengkapitalisasinya menggunakan fungsi dari tugas pertama.

  • Kita dapat melakukannya seperti ini:

    words.iter().map(|word| capitalize_first(word)).collect()

    collect() dapat mengambil apa pun yang iterable, dan mengubahnya menjadi koleksi yang relevan.

  • Dalam kasus ini Rust akan mengonversi iterator ke tipe kembalian yang diinginkan yaitu Vec<String>.

  • Ini juga berarti kita dapat menggunakan kode yang sama untuk tugas kita selanjutnya di fungsi capitalize_words_string dan Rust akan mengonversi iterator ke tipe kembalian yang diinginkan yaitu String.

iterators3.rs

#[derive(Debug, PartialEq, Eq)]
enum DivisionError {
    // Example: 42 / 0
    DivideByZero,
    // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
    IntegerOverflow,
    // Example: 5 / 2 = 2.5
    NotDivisible,
}

// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
    if b == 0 {
        return Err(DivisionError::DivideByZero);
    }
    let (r, overflow) = a.overflowing_div(b);
    if overflow {
        return Err(DivisionError::IntegerOverflow);
    }
    if a % b != 0 {
        return Err(DivisionError::NotDivisible);
    }
    Ok(r)
}

// Add the correct return type and complete the function body.
// Desired output: `Ok([1, 11, 1426, 3])`
fn result_with_list() -> Result<Vec<i64>, DivisionError> {
    let numbers = [27, 297, 38502, 81];
    let division_results = numbers.into_iter().map(|n| divide(n, 27));
    division_results.into_iter().collect()
}

// Add the correct return type and complete the function body.
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
fn list_of_results() -> Vec<Result<i64, DivisionError>> {
    let numbers = [27, 297, 38502, 81];
    let division_results = numbers.into_iter().map(|n| divide(n, 27));
    division_results.into_iter().collect()
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_success() {
        assert_eq!(divide(81, 9), Ok(9));
    }

    #[test]
    fn test_divide_by_0() {
        assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
    }

    #[test]
    fn test_integer_overflow() {
        assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
    }

    #[test]
    fn test_not_divisible() {
        assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));
    }

    #[test]
    fn test_divide_0_by_something() {
        assert_eq!(divide(0, 81), Ok(0));
    }

    #[test]
    fn test_result_with_list() {
        assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]);
    }

    #[test]
    fn test_list_of_results() {
        assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]);
    }
}
  • Tugas pertama di latihan ini adalah melengkapi fungsi divide untuk mengembalikan error sesuai dengan enum DivisionError.

  • Untuk pemeriksaan overflow kita dapat melakukannya dengan menggunakan method overflowing_div.

    if b == 0 {
        return Err(DivisionError::DivideByZero);
    }
    let (r, overflow) = a.overflowing_div(b);
    if overflow {
        return Err(DivisionError::IntegerOverflow);
    }
    if a % b != 0 {
        return Err(DivisionError::NotDivisible);
    }
    Ok(r)
  • Tugas kedua adalah memperbaiki fungsi result_with_list.

    • Signature kembalian yang memenuhi output yang diinginkan harus Result<Vec<i64>, DivisionError>.
    • Dan kita dapat menggunakan rantai method into_iter().collect() untuk mengonversi iterator ke output yang diinginkan.
  • Mirip seperti tugas sebelumnya, tugas terakhir adalah memperbaiki fungsi list_of_results.

    • Signature kembalian yang memenuhi output yang diinginkan harus Vec<Result<i64, DivisionError>>.
    • Dan kita dapat menggunakan rantai method into_iter().collect() untuk mengonversi iterator ke output yang diinginkan.

iterators4.rs

fn factorial(num: u64) -> u64 {
    // Complete this function to return the factorial of `num` which is
    // defined as `1 * 2 * 3 * … * num`.
    // https://en.wikipedia.org/wiki/Factorial
    //
    // Do not use:
    // - early returns (using the `return` keyword explicitly)
    // Try not to use:
    // - imperative style loops (for/while)
    // - additional variables
    // For an extra challenge, don't use:
    // - recursion
    // (1..=num).fold(1, |r, x| r * x)
    (1..=num).product()
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn factorial_of_0() {
        assert_eq!(factorial(0), 1);
    }

    #[test]
    fn factorial_of_1() {
        assert_eq!(factorial(1), 1);
    }
    #[test]
    fn factorial_of_2() {
        assert_eq!(factorial(2), 2);
    }

    #[test]
    fn factorial_of_4() {
        assert_eq!(factorial(4), 24);
    }
}
  • Latihan ini cukup lurus, kita hanya perlu menyelesaikan fungsi factorial.

  • Kita dapat menggunakan method fold untuk melakukan ini.

    Melipat setiap elemen ke dalam akumulator dengan menerapkan operasi, mengembalikan hasil akhir.

    (1..=num).fold(1, |r, x| r * x)
  • Tapi kemudian kamu akan melihat bahwa compiler Rust akan menyarankan untuk menggunakan product sebagai gantinya seperti ini:

    Melakukan iterasi seluruh iterator, mengalikan semua elemen

    (1..=num).product()

iterators5.rs

// Let's define a simple model to track Rustlings' exercise progress. Progress
// will be modelled using a hash map. The name of the exercise is the key and
// the progress is the value. Two counting functions were created to count the
// number of exercises with a given progress. Recreate this counting
// functionality using iterators. Try to not use imperative loops (for/while).

use std::collections::HashMap;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Progress {
    None,
    Some,
    Complete,
}

fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
    let mut count = 0;
    for val in map.values() {
        if *val == value {
            count += 1;
        }
    }
    count
}

// Implement the functionality of `count_for` but with an iterator instead
// of a `for` loop.
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
    // `map` is a hash map with `String` keys and `Progress` values.
    // map = { "variables1": Complete, "from_str": None, … }
    map.iter()
        .map(|(_k, p)| if *p == value { 1 } else { 0 })
        .sum()
}

fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
    let mut count = 0;
    for map in collection {
        for val in map.values() {
            if *val == value {
                count += 1;
            }
        }
    }
    count
}

// Implement the functionality of `count_collection_for` but with an
// iterator instead of a `for` loop.
fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
    // `collection` is a slice of hash maps.
    // collection = [{ "variables1": Complete, "from_str": None, … },
    //               { "variables2": Complete, … }, … ]
    collection.iter().map(|m| count_iterator(m, value)).sum()
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get_map() -> HashMap<String, Progress> {
        use Progress::*;

        let mut map = HashMap::new();
        map.insert(String::from("variables1"), Complete);
        map.insert(String::from("functions1"), Complete);
        map.insert(String::from("hashmap1"), Complete);
        map.insert(String::from("arc1"), Some);
        map.insert(String::from("as_ref_mut"), None);
        map.insert(String::from("from_str"), None);

        map
    }

    fn get_vec_map() -> Vec<HashMap<String, Progress>> {
        use Progress::*;

        let map = get_map();

        let mut other = HashMap::new();
        other.insert(String::from("variables2"), Complete);
        other.insert(String::from("functions2"), Complete);
        other.insert(String::from("if1"), Complete);
        other.insert(String::from("from_into"), None);
        other.insert(String::from("try_from_into"), None);

        vec![map, other]
    }

    #[test]
    fn count_complete() {
        let map = get_map();
        assert_eq!(count_iterator(&map, Progress::Complete), 3);
    }

    #[test]
    fn count_some() {
        let map = get_map();
        assert_eq!(count_iterator(&map, Progress::Some), 1);
    }

    #[test]
    fn count_none() {
        let map = get_map();
        assert_eq!(count_iterator(&map, Progress::None), 2);
    }

    #[test]
    fn count_complete_equals_for() {
        let map = get_map();
        let progress_states = [Progress::Complete, Progress::Some, Progress::None];
        for progress_state in progress_states {
            assert_eq!(
                count_for(&map, progress_state),
                count_iterator(&map, progress_state),
            );
        }
    }

    #[test]
    fn count_collection_complete() {
        let collection = get_vec_map();
        assert_eq!(
            count_collection_iterator(&collection, Progress::Complete),
            6,
        );
    }

    #[test]
    fn count_collection_some() {
        let collection = get_vec_map();
        assert_eq!(count_collection_iterator(&collection, Progress::Some), 1);
    }

    #[test]
    fn count_collection_none() {
        let collection = get_vec_map();
        assert_eq!(count_collection_iterator(&collection, Progress::None), 4);
    }

    #[test]
    fn count_collection_equals_for() {
        let collection = get_vec_map();
        let progress_states = [Progress::Complete, Progress::Some, Progress::None];

        for progress_state in progress_states {
            assert_eq!(
                count_collection_for(&collection, progress_state),
                count_collection_iterator(&collection, progress_state),
            );
        }
    }
}
  • Latihan ini mungkin terlihat menakutkan tapi cukup sederhana.

  • Pertama kita perlu melengkapi fungsi count_iterator.

    • Pada dasarnya kita perlu mengembalikan hitungan nilai hashmap yang diberikan yang cocok dengan Progress yang diberikan.
    • Kita dapat menggunakan iterator, memetakannya, lalu menghitung jumlahnya seperti ini:
    map.iter().map(|(_k, p)| if *p == value { 1 } else { 0 }).sum()
  • Kedua kita perlu melengkapi fungsi count_collection_iterator.

    • Pada dasarnya untuk setiap hashmap dalam koleksi yang diberikan kita perlu menghitung progress yang cocok dan menjumlahkannya.
    • Mirip seperti tugas pertama, kita bisa iter, map, lalu sum seperti ini:
    collection.iter().map(|m| count_iterator(m, value)).sum()

Edit on GitHub

Last updated on

Iterators | Faisal Affan