Last active
April 28, 2018 14:57
-
-
Save segfo/935cf0c0c723247c91ea7188fa94f27b to your computer and use it in GitHub Desktop.
forを使わずにfizzbuzzしたり、奇数だけを2倍して表示したり。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main(){ | |
let n = (0..20).collect::<Vec<u32>>(); | |
let v = n.iter().filter(|n|(*n)%2==1).map(|n|n*2).collect::<Vec<u32>>(); | |
let fb = n.iter().map(fizzbuzz).collect::<Vec<String>>(); | |
println!("{:?}",v); | |
println!("{:?}",fb); | |
//もっとスマートに書くと | |
println!("{:?}",(0..20).filter(|n|(*n)%2==1).map(|n| n * n).collect::<Vec<u32>>()); | |
println!("{:?}",(0..20).map(fizzbuzz).collect::<Vec<String>>()); | |
// もっともーっとスマートに(Vecを一切使わない) | |
(0..20).filter_map(|n|if n%2==1{Some(n*n)}else{None}).for_each(|n|print!("{}, ",n)); | |
println!(""); | |
(0..20).map(fizzbuzz).for_each(|n|print!("{}, ",n)); | |
println!(""); | |
} | |
fn fizzbuzz(n:&u32)->String{ | |
match n{ | |
n if n%3==0&&n%5==0 =>"fizz buzz".to_owned(), | |
n if n%3==0 =>"fizz".to_owned(), | |
n if n%5==0 =>"buzz".to_owned(), | |
n => n.to_string() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment