Haskell中的Fibonacci数

时间:2010-05-10 15:28:29

标签: haskell

大家好我需要将我的F#代码更改为Haskell代码,但我在Haskell中是如此新,我不能这样我的代码只是从键盘读取数据,如果数据不是整数返回错误消息然后计算n斐波那契数字然后在将列表写入txt文件之后写入列表这是我的代码

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 writeToFile list = 
    let file = System.IO.File.Create("C:\out2.txt")
    let mutable s =""
    let writer = new System.IO.StreamWriter(file)
    try
        for i=0 to (List.length list)-1 do
        s <- list.Item(i).ToString()
        writer.Write(s+" ")

    finally
        writer.Close()
        file.Dispose()
        printfn "Writed To File"


let mutable control = true
let mutable num = 0
while control do 
    try
    printfn "Enter a Number:" 

    num <- Convert.ToInt32(stdin.ReadLine()) 
    let listFibonacci = [for i in 0 .. num-1->fib(i)]
    printFibonacci(listFibonacci)
    printfn "\n%A"(listFibonacci)
    writeToFile(listFibonacci)
    control<-false
    with
        | :? System.FormatException->printfn "Number Format Exception";

Console.ReadKey true|>ignore

2 个答案:

答案 0 :(得分:15)

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

main = do putStrLn "Enter a number:"
          num <- readLn
          fibs = map fib [0..n]
          mapM' print fibs

然而,由于haskell很懒惰,因此有一种聪明的方法可以定义所有斐波纳契数列表。而且由于您需要该列表的前缀,因此使用此定义更自然(也更高效):

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

main = do putStrLn "Enter a number:"
          num <- readLn
          mapM' print (take n fibs)

编辑:要使用print(\num -> appendFile "filename" (show num))来写入文件而不是stdout替换(appendFile "filename" . show)

答案 1 :(得分:2)

这基本上是序列本身最常见的实现:

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

如果你想要键盘上的数字:

main :: IO ()
main = catch doFib handle
   where doFib = do
            num <- readLn
            putStrLn $ "Fib of " ++ show num ++ " = " ++ (show . fib $ num)
         handle _ -> putStrLn "Malformed input!"

完成!