Created
January 6, 2013 17:07
-
-
Save anonymous/4468677 to your computer and use it in GitHub Desktop.
A simple string-to-float function showing how beautiful rust's pattern matching is.
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
enum ParsedFloat { | |
FloatValue(float), | |
FloatSyntaxError, | |
} | |
enum FloatParserState { | |
BeforeSign, | |
BeforeDot, | |
AfterDot, | |
Stop, | |
} | |
// return the number of parsed characters | |
fn parseFloat(src: &str, result:& mut ParsedFloat) -> uint { | |
let mut state = BeforeSign; | |
let mut value = 0.0; | |
let mut sign = 1.0; | |
let mut decimals = 0.1; | |
let mut count = 0; | |
for src.each_char | c | { | |
match (state, c) { | |
(Stop, _) => { break; }, | |
(BeforeSign, '-') => { | |
state = BeforeDot; | |
sign = -1.0; | |
}, | |
(BeforeSign, '0'..'9') | (BeforeDot, '0'..'9') => { | |
value = value * 10.0 + (((c as int) - ('0' as int)) as float); | |
state = BeforeDot; | |
}, | |
(BeforeSign, ' ') => {}, | |
(BeforeDot, '.') => { state = AfterDot; } | |
(AfterDot, '0'..'9') => { | |
value += (((c as int) - ('0' as int)) as float) * decimals; | |
decimals /= 10.0; | |
}, | |
(AfterDot, ' ') => { state = Stop; }, | |
(_,_) => { | |
*result = FloatSyntaxError; | |
return 0; | |
}, | |
} | |
count += 1; | |
} | |
value *= sign; | |
*result = FloatValue(value); | |
return count; | |
} | |
fn toFloat(s: &str) -> float { | |
let mut result : ParsedFloat = FloatSyntaxError; | |
parseFloat(s, &mut result); | |
match result { | |
FloatValue(v) => return v, | |
FloatSyntaxError => fail, | |
} | |
} | |
fn main() { | |
io::println(fmt!("%f", toFloat(~"12345"))); | |
io::println(fmt!("%f", toFloat(~" 12.345 "))); | |
io::println(fmt!("%f", toFloat(~"-12345"))); | |
io::println(fmt!("%f", toFloat(~"0"))); | |
io::println(fmt!("%f", toFloat(~" -0.0120 "))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment