Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,12 +1,17 @@
fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) {
// Works with 0.13.0-dev (f673e9841)
fn fib<F>(n: i64, f: F) -> (i64, i64) where F: Fn(i64) {
if n < 0 {
// Let these variables be mutated, otherwise too slow
let mut n1:i64 = 0, n2:i64 = -1, i:int = 0, tmp:i64;
let mut n1:i64 = 0;
let mut n2:i64 = -1;
let mut i:i64 = 0;
let mut tmp:i64;
while i > n {
f(n1);
tmp = n1-n2;
if (tmp > 0 && n2 > 0) { //Detect overflow
io::println("\nReached the limit of i64, halting");
if tmp > 0 && n2 > 0 { //Detect overflow
println!("\nReached the limit of i64, halting");
return (n1, i);
}
n1 = n2;
@ -16,12 +21,16 @@ fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) {
(n1+n2, n)
} else if n > 0 {
// And these variables
let mut n1:i64 = 0, n2:i64 = 1, i:int = 0, tmp:i64;
let mut n1:i64 = 0;
let mut n2:i64 = 1;
let mut i:i64 = 0;
let mut tmp:i64;
while i < n {
f(n1);
tmp = n1+n2;
if (tmp < 0) { //Detect overflow
io::println("\nReached the limit of i64, halting");
if tmp < 0 { //Detect overflow
println!("\nReached the limit of i64, halting");
return (n1, i);
}
n1 = n2;
@ -36,21 +45,11 @@ fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) {
}
fn main() {
let args = os::args();
let n = if args.len() == 1 {
10
} else if args.len() > 1 {
// Convert from a string
match (int::from_str(args[1])) {
Some(num) => num,
None => 10 //Fall back to default
}
} else {
/* Required to use the if as an expression.
* We know that args.len() is always >= 1, the compiler
* does not. fail lets it know that we can't get past here.
*/
fail ~"No arguments given, somehow...";
let args = std::os::args();
let default_n = 10i64;
let n = match args.len() {
1 => default_n,
_ => args[1].parse().unwrap_or(default_n)
};
/* Use the loop protocol to be able to do things
@ -58,10 +57,10 @@ fn main() {
* The loop itself returns a tuple with where it got to and
* what the number is.
*/
let (result, n) = for fib(n) |num| {
let (result, n) = fib(n, |num| {
//print out the sequence
io::print(fmt!("%? ", num));
};
print!("{} ", num);
});
io::println(fmt!("\nThe %dth fibonacci number is: %?", n, result));
println!("\nThe {}th fibonacci number is: {}", n, result);
}

View file

@ -1,19 +1,17 @@
// Works with 0.13.0-dev (f673e9841)
fn main() {
fn fib(n: int) -> int {
fn _fib(n: int, a: int, b: int) -> int {
match (n, a, b) {
(0, _, _) => a,
_ => _fib(n-1, a+b, a)
}
}
fn fib(n: int) -> int {
_fib(n, 0, 1)
}
fn _fib(n: int, a: int, b: int) -> int {
match (n, a, b) {
(0, _, _) => a,
_ => _fib(n-1, a+b, a)
}
}
_fib(n, 0, 1)
}
for n in range(0,20) {
println(fmt!("%d", fib(n)))
}
for n in range(0, 20) {
println!("{}", fib(n));
}
}