gpt4 book ai didi

haskell - 重复计时功能

转载 作者:行者123 更新时间:2023-12-02 15:23:18 25 4
gpt4 key购买 nike

我有一个非常简单的函数 f::Int -> Int,我想编写一个程序,为每个 n = 1,2 调用 f ,...,最大。每次调用 f 后,应显示到该点为止所用的(累积)时间(以及 nf n)。如何实现?

我对 Haskell 的输入/输出还很陌生,所以这就是我到目前为止所尝试的(使用一些玩具示例函数 f)

f :: Int -> Int
f n = sum [1..n]

evalAndTimeFirstN :: Int -> Int -> Int -> IO()
evalAndTimeFirstN n max time =
if n == max
then return () -- in the following we have to calculate the time difference from start to now
else let str = ("(" ++ (show n) ++ ", " ++ (show $ f n) ++ ", "++ (show time)++ ")\n")
in putStrLn str >> evalAndTimeFirstN (n+1) max time -- here we have to calculate the time difference

main :: IO()
main = evalAndTimeFirstN 1 5 0

我不太明白如何在这里介绍时间安排。 (时间Int可能需要用其他东西替换。)

最佳答案

您可能想要这样的东西。根据您的递归函数的需要调整以下基本示例。

import Data.Time.Clock
import Control.Exception (evaluate)

main :: IO ()
main = do
putStrLn "Enter a number"
n <- readLn
start <- getCurrentTime
let fact = product [1..n] :: Integer
evaluate fact -- this is needed, otherwise laziness would postpone the evaluation
end <- getCurrentTime
putStrLn $ "Time elapsed: " ++ show (diffUTCTime end start)
-- putStrLn $ "The result was " ++ show fact

取消注释最后一行以打印结果(它很快就会变得非常大)。

关于haskell - 重复计时功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44377763/

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