Tuesday, October 19, 2010

F# TIMTOWTDI : fibonacci

1st step

let defines function, and let rec defines recursive function.
> let rec fibonacci n = if n=0 then 0 elif n=1 then 1 else fibonacci(n-2) + fibonacci(n-1);;
> for i in [0..10] do
-     let fibn = fibonacci i
-     printfn "%d" fibn
- done;;
0
1
1
2
3
5
8
13
21
34
55
val it : unit = ()

2nd step

Erase elif phrase.
> let rec fibonacci n = if n<=1 then n else fibonacci(n-2) + fibonacci(n-1);;
> for i in [0..10] do
-     let fibn = fibonacci i
-     printfn "%d" fibn
- done;;
0
1
1
2
3
5
8
13
21
34
55
val it : unit = ()

3rd step

Use match with phrase (same as Ruby's case-when phrase).
> let rec fibonacci n =
-     match n with
-     | 0 | 1 -> n
-     | _     -> fibonacci(n-2) + fibonacci(n-1);;
> for i in [0..10] do
-     let fibn = fibonacci i
-     printfn "%d" fibn
- done;;
0
1
1
2
3
5
8
13
21
34
55
val it : unit = ()

No comments:

Post a Comment