gpt4 book ai didi

haskell - Haskell 中的斐波那契数列

转载 作者:行者123 更新时间:2023-12-01 07:08:33 26 4
gpt4 key购买 nike

大家好,我需要将我的 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

最佳答案

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))(appendFile "filename" . show) .

关于haskell - Haskell 中的斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2803920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com