Created
October 7, 2012 16:35
-
-
Save andrewvc/3848855 to your computer and use it in GitHub Desktop.
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
use std; | |
import io::println; | |
import io::reader_util; | |
type birth_row = { | |
prglength: int, | |
outcome: int, | |
birthord: int}; | |
type birth_group_stats = @{mut count: int, mut prglength_total: int, mut prglength_avg: float}; | |
type birth_groups = {first_born: birth_group_stats, nth_born: birth_group_stats}; | |
fn empty_birth_group_stat () -> birth_group_stats { | |
ret @{mut count: 0, mut prglength_total: 0, mut prglength_avg: 0.0}; | |
} | |
fn empty_birth_groups () -> birth_groups { | |
ret {first_born: empty_birth_group_stat(), nth_born: empty_birth_group_stat()}; | |
} | |
fn int_parse_slice(s: str, start: uint, end: uint) -> int { | |
let trimmed = str::trim(s.slice(start, end)); | |
if trimmed.len() < 1 { ret -1 }; | |
let res = int::from_str(trimmed).expect("Something happened"); | |
ret res; | |
} | |
fn load_data() -> ~[birth_row] { | |
let path = "2002FemPreg.dat", | |
rdr = io::file_reader(path); | |
assert result::is_ok(rdr); | |
let rdr = result::get(rdr); | |
let mut births: ~[birth_row] = ~[]; | |
loop { | |
let line = rdr.read_line(); | |
if rdr.eof() { break }; | |
let b: birth_row = { | |
prglength: int_parse_slice(line, 274,276), | |
outcome: int_parse_slice(line, 276,277), | |
birthord: int_parse_slice(line, 277,279) | |
}; | |
vec::push(births, b) | |
} | |
ret births; | |
} | |
fn calculate_aggregates(births: ~[birth_row]) -> birth_groups { | |
let groups = empty_birth_groups(); | |
for births.each |b| { | |
if b.outcome == 1 { | |
let g: birth_group_stats = if b.birthord == 1 { groups.first_born } | |
else { groups.nth_born }; | |
g.count += 1; | |
g.prglength_total += b.prglength; | |
} | |
}; | |
let group_stats = ~[groups.first_born, groups.nth_born]; | |
for group_stats.each |g| { | |
g.prglength_avg = (g.prglength_total as float) / (g.count as float); | |
} | |
ret groups; | |
} | |
fn main () { | |
println("Loading data.."); | |
let birth_data = load_data(); | |
println("Calculating aggregates..."); | |
let groups = calculate_aggregates(birth_data); | |
println("Results:\n"); | |
println("First Borns: " + int::str(groups.first_born.count)); | |
println(#fmt("First Born AVG prglength: %f", groups.first_born.prglength_avg)); | |
println("Nth Borns: " + int::str(groups.nth_born.count)); | |
println(#fmt("Nth Born AVG prglength: %f", groups.nth_born.prglength_avg)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment