Skip to content

Commit 71abb16

Browse files
committed
added collections and string examples
1 parent 26e0a14 commit 71abb16

File tree

8 files changed

+170
-0
lines changed

8 files changed

+170
-0
lines changed

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,8 @@ in a controlled repository now.
3434
* `negiter/`: example iterator adapter
3535
* `stackcoll/`: example fromiterator implementation
3636
* `shuflr/`: example iterator implementation
37+
* `seqs.rs`: examples with sequence types
38+
* `vecdeque.rs`: example of `VecDeque` usage
39+
* `setimpl.rs`: example implementation of `HashSet` as `HashMap`
40+
* `rng/`: example use of `rand` crate
41+
* `charcast.rs`: character / number casting examples

charcast.rs

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fn main() {
2+
println!("{:02x}", 'x' as u8);
3+
println!("{:02x}", '🦀' as u8);
4+
println!("{:02x}", '🦀' as i8);
5+
println!("{:04x}", '🦀' as u16);
6+
println!("{:08x}", '🦀' as u32);
7+
println!("{:08x}", '🦀' as i32);
8+
println!("{:016x}", '🦀' as u64);
9+
10+
println!("{}", 0x78u8 as char);
11+
}

histogram.rs

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Copyright © 2018 Bart Massey
2+
// [This program is licensed under the "MIT License"]
3+
// Please see the file LICENSE in the source
4+
// distribution of this software for license terms.
5+
6+
use std::collections::HashMap;
7+
use std::fmt;
8+
use std::fs::File;
9+
use std::hash::Hash;
10+
use std::io::Read;
11+
use std::iter::FromIterator;
12+
13+
#[derive(Clone, Debug)]
14+
struct Histogram<T: Hash + Eq>(HashMap<T, usize>);
15+
16+
impl<T: Hash + Eq> Histogram<T> {
17+
fn histogram<I>(values: I) -> Self
18+
where
19+
I: IntoIterator<Item = T>,
20+
{
21+
let mut h = HashMap::new();
22+
for k in values {
23+
h.entry(k).and_modify(|e| *e += 1).or_insert(1);
24+
}
25+
Histogram(h)
26+
}
27+
}
28+
29+
impl<T: Hash + Eq + Ord> Histogram<T> {
30+
fn graph<'a>(&'a self) -> Vec<(&'a T, usize)> {
31+
let Histogram(h) = self;
32+
let mut result: Vec<(&T, usize)> =
33+
h.iter().map(|(k, v)| (k, *v)).collect();
34+
result.sort();
35+
result
36+
}
37+
}
38+
39+
impl<T: Hash + Eq> FromIterator<T> for Histogram<T> {
40+
fn from_iter<I>(iter: I) -> Self
41+
where
42+
I: IntoIterator<Item = T>,
43+
{
44+
Histogram::histogram(iter)
45+
}
46+
}
47+
48+
impl<T> fmt::Display for Histogram<T>
49+
where
50+
T: Hash + Eq + Ord + fmt::Debug,
51+
{
52+
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
53+
for (key, count) in self.graph() {
54+
writeln!(fmt, "{:?}: {}", key, count)?;
55+
}
56+
Ok(())
57+
}
58+
}
59+
60+
fn clean_chars(s: &str) -> String {
61+
let mut result = String::new();
62+
for c in s.chars() {
63+
if c.is_alphabetic() || c.is_numeric() || c.is_whitespace() {
64+
result.extend(c.to_lowercase());
65+
} else {
66+
result.push(' ');
67+
}
68+
}
69+
result
70+
}
71+
72+
fn main() {
73+
let h: Histogram<char> = "hello world"
74+
.chars()
75+
.filter(|c| c.is_alphabetic())
76+
.collect();
77+
println!("{}", h);
78+
79+
let words: Histogram<&str> = "a banana is a banana is a banana"
80+
.split_whitespace()
81+
.collect();
82+
println!("{}", words);
83+
84+
let mut gba = String::new();
85+
File::open("gettysburg-address.txt")
86+
.expect("file not found")
87+
.read_to_string(&mut gba)
88+
.expect("file read error");
89+
let gba = clean_chars(&gba);
90+
let gba: Histogram<&str> = gba.split_whitespace().collect();
91+
println!("{}", gba);
92+
}

rng/Cargo.toml

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[package]
2+
name = "rng"
3+
version = "0.1.0"
4+
authors = ["Bart Massey <[email protected]>"]
5+
edition = "2018"
6+
7+
[dependencies]
8+
rand = "0.8"
9+
10+
[[bin]]
11+
name = "rng"
12+
path = "rng.rs"

rng/rng.rs

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
use rand::Rng;
2+
3+
fn main() {
4+
for _ in 0..10 {
5+
println!("{}", rand::thread_rng().gen_range(1..=6));
6+
}
7+
}

seqs.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
fn main() {
2+
let mut v: Vec<&'static str> = Vec::new();
3+
v.push("hello");
4+
v.push("world");
5+
println!("{:?}", v);
6+
println!("{:?}", &v);
7+
let w = vec!["hello", "world"];
8+
assert_eq!(v, w);
9+
10+
let a: [&'static str; 2] = ["hello", "world"];
11+
println!("{:?}", a);
12+
let b: [&'static str; 2] = ["hello", "world"];
13+
assert_eq!(a, b);
14+
15+
let s: &[&'static str] = &v;
16+
let t: &[&'static str] = &a;
17+
18+
assert_eq!(s, t);
19+
assert_eq!(s.len(), t.len());
20+
}

setimpl.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
use std::collections::HashMap;
2+
3+
pub type MyHashSet<T> = HashMap<T, ()>;
4+
5+
#[test]
6+
fn test_my_hash_set() {
7+
let mut t: MyHashSet<u32> = HashMap::new();
8+
t.insert(3, ());
9+
t.insert(2, ());
10+
t.insert(3, ());
11+
let u: MyHashSet<u32> = vec![(2, ()), (3, ())].into_iter().collect();
12+
assert_eq!(t, u);
13+
}

vecdeque.rs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
use std::collections::VecDeque;
2+
3+
fn main() {
4+
let mut q = VecDeque::new();
5+
q.push_back(1u32);
6+
q.push_back(2);
7+
println!("{}", q.pop_front().unwrap());
8+
println!("{}", q.pop_front().unwrap());
9+
assert_eq!(q.pop_front(), None);
10+
}

0 commit comments

Comments
 (0)