Zettazebra

Version 5.0

Most scripts I write are write once, use many.

Unfortunately, this means that for some things that I wrote years ago...I have no idea how they work.

Take for example an alias I wrote to take the average of a series of numbers:

alias avg='tr "\n" " " |sed -e "s/\(-\)\([0-9.]*\)/\2\1/g" |dc -e "? z sc [+ z 1 !>b]sa  [z 2 !>a]sb lax lc 2 k / p"'

I get the tr and sed bits - I use those tools all the time. However, I no longer posess a working knowledge of dc. I know it's sticking stuff into registers and operating on them in some way, but the details completely escape me.

Several years ago, I replaced this with utility I wrote in rust:

use std::io::BufRead;
use std::io::BufReader;
use std::io::stdin;
use std::io::Error;

fn get_number(line: Result<String, Error>) -> Option<f64> {
    match line {
        Err(_) => None,
        Ok(text) => match text.parse::<f64>() {
            Err(_) => None,
            Ok(val) => Some(val)
        }
    }
}

fn main() {
    let mut total = 0.0;
    let mut count = 0.0;
    let numbers = BufReader::new(stdin()).lines().filter_map(get_number);
    for (idx, num) in numbers.enumerate() {
        let index = idx as f64;
        count = index + 1.0;
        total += num;
    }
    println!("{}", total/count);
}

Compiled + stripped it weighs in at 272KB, but I prefer knowing what it does.