Skip to content

Commit e8dc51e

Browse files
authored
Merge pull request #406 from o0Ignition0o/fib_example
Fibonacci sequence example.
2 parents cc33f01 + 226663e commit e8dc51e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

examples/fib.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use async_std::task;
2+
use tide::Request;
3+
4+
fn fib(n: usize) -> usize {
5+
if n == 0 || n == 1 {
6+
n
7+
} else {
8+
fib(n - 1) + fib(n - 2)
9+
}
10+
}
11+
12+
async fn fibsum(req: Request<()>) -> String {
13+
use std::time::Instant;
14+
let n: usize = req.param("n").unwrap_or(0);
15+
// Start a stopwatch
16+
let start = Instant::now();
17+
// Compute the nth number in the fibonacci sequence
18+
let fib_n = fib(n);
19+
// Stop the stopwatch
20+
let duration = Instant::now().duration_since(start).as_secs();
21+
// Return the answer
22+
format!(
23+
"The fib of {} is {}.\nIt was computed in {} secs.\n",
24+
n, fib_n, duration,
25+
)
26+
}
27+
// Example: HTTP GET to http://localhost:8080/fib/42
28+
// $ curl "http://localhost:8080/fib/42"
29+
// The fib of 42 is 267914296.
30+
// It was computed in 2 secs.
31+
fn main() -> Result<(), std::io::Error> {
32+
task::block_on(async {
33+
let mut app = tide::new();
34+
app.at("/fib/:n").get(fibsum);
35+
app.listen("0.0.0.0:8080").await?;
36+
Ok(())
37+
})
38+
}

0 commit comments

Comments
 (0)