Created
March 23, 2015 21:50
-
-
Save steveklabnik/690683d4cb8cbd933736 to your computer and use it in GitHub Desktop.
a little wc-like in rust
This file contains 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
#![feature(collections)] | |
use std::io::prelude::*; | |
use std::fs::File; | |
use std::io::BufReader; | |
fn main() { | |
let args: Vec<String> = std::env::args().collect(); | |
let filename = args[1].clone(); | |
let file = File::open(&filename).ok().expect("I couldn't open that file, sorry :("); | |
let reader = BufReader::new(file); | |
let words = reader.split(b' ') | |
.map(|x| x.ok().expect("There was an IO error.")) | |
.count(); | |
println!("words: {}", words); | |
let file = File::open(&filename).ok().expect("I couldn't open that file, sorry :("); | |
let newlines = file.bytes() | |
.map(|x| x.ok().expect("There was an IO error.")) | |
.filter(|x| *x == b'\n') | |
.count(); | |
println!("newlines: {}", newlines) | |
} |
I'd love to see a Reactive stream version of that (Rx stuff) ...
- one stage to turn the file into lines (
map
)- and a
count
for that - and a second stage that turns the lines into words
concat_map
(I'm really not sure, I'm just dabbling with Rx so far).- and a
count
for that.
- and a
- and a
It would be a single pass and would be "functional" (as far as the client code goes).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I couldn't resist playing golf with that. This is less clear, and less "functional" but is possibly? more efficient and concise: