如果我正確理解你的代碼,你想繼續詢問輸入數字n,直到給出一個有效的數字並打印斐波那契數字爲n。在這種情況下,您最好在try塊內移動計算和打印。這是格式化的更新版本。
open System
let rec fib n =
match n with
|0->0
|1->1
|2->1
|n->fib(n-1)+fib(n-2);;
let printFibonacci list =
for i=0 to (List.length list)-1 do
printf "%d " (list.Item(i))
let mutable control = true //you forgot to add the 'mutable' keyword
while control do
try
printfn "Enter a Number:"
let num:int = Convert.ToInt32(stdin.ReadLine())
let listFibonacci = [for i in 0 .. num-1 -> fib(i)]
printFibonacci(listFibonacci)
printfn "\n%A"(listFibonacci)
control <- false
with
| :? System.FormatException -> printfn "Number Format Exception"
//add the ignore statement to drop the resulting ConsoleKeyInfo struct
//or the compiler will complain about an unused value floating around.
Console.ReadKey(true) |> ignore
// exit 0 (* Exit isn't necessary *)
而不是使用命令行式風格號碼輸入程序,依靠控制流異常,這裏是一個遞歸函數getNumberFromConsole你可以使用,以及:
open System
let rec fib n =
match n with
| 0 -> 0
| 1 | 2 -> 1
| n -> fib(n-1) + fib(n-2);;
let printFibonacci list =
for i=0 to (List.length list)-1 do
printf "%d " (list.Item(i))
//alternative number input, using recursion
let rec getNumberFromConsole() =
match Int32.TryParse(stdin.ReadLine()) with
| (true, value) -> value
| (false, _) -> printfn "Please enter a valid number"
getNumberFromConsole()
printfn "Enter a Number:"
let num = getNumberFromConsole()
let listFibonacci = [for i in 0 .. num-1 -> fib(i)]
printFibonacci(listFibonacci)
printfn "\n%A"(listFibonacci)
Console.ReadKey(true) |> ignore
附:感謝您給我看stdin
。我從來不知道它存在。現在我可以編寫一些交互式腳本。
請檢查格式並在必要時進行更正,我對F#不熟悉足以確定哪些部分應該正確縮進。我所做的只是縮進代碼4個空格,以便讓SO代碼格式化系統起作用。 – 2010-05-09 10:46:55