Facebook
From Blush Camel, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 103
  1. Ich:
  2.         Write a Rust program that takes a string formatted list
  3.     of integers as an environment variable and calculates the
  4.     sum of the squares of these values and prints the result out
  5.  
  6. GPT:
  7.     Here's an example Rust program that does that:
  8.    
  9.     ```
  10.     Copy code
  11.     use std::env;
  12.    
  13.     fn main() {
  14.         let args: Vec<String> = env::args().collect();
  15.         let list = match env::var("INT_LIST") {
  16.             Ok(val) => val,
  17.             Err(_e) => {
  18.                 println!("INT_LIST environment variable not set.");
  19.                 return;
  20.             }
  21.         };
  22.    
  23.         let int_list: Vec<i32> = list
  24.             .split(",")
  25.             .map(|s| s.trim().parse().unwrap_or(0))
  26.             .collect();
  27.    
  28.         let sum = int_list.iter().map(|x| x * x).sum();
  29.    
  30.         println!("The sum of the squares of the values is: {}", sum);
  31.     }
  32.     ```
  33.     This program first retrieves the environment variable named INT_LIST using the env::var function. If the environment variable is not set, an error message is printed and the program returns.
  34.        
  35.     Otherwise, the string value of the environment variable is split by commas into a vector of strings and then each string is parsed as an i32 value. If a string can't be parsed, it's treated as 0.
  36.    
  37.     Finally, the squares of the i32 values are calculated using the map and sum functions, and the result is printed.
  38.  
  39. Ich:
  40.         This snippet doesn't compile because the sum variable needs a type hint
  41.    
  42. GPT:
  43.         Here's an updated version that includes a type hint for the sum variable:
  44.    
  45.     ```
  46.     use std::env;
  47.        
  48.     fn main() {
  49.         let args: Vec<String> = env::args().collect();
  50.         let list = match env::var("INT_LIST") {
  51.             Ok(val) => val,
  52.             Err(_e) => {
  53.                 println!("INT_LIST environment variable not set.");
  54.                 return;
  55.             }
  56.         };
  57.    
  58.         let int_list: Vec<i32> = list
  59.             .split(",")
  60.             .map(|s| s.trim().parse().unwrap_or(0))
  61.             .collect();
  62.    
  63.         let sum: i32 = int_list.iter().map(|x| x * x).sum();
  64.    
  65.         println!("The sum of the squares of the values is: {}", sum);
  66.     }
  67. ```
  68.