我想找出滿足的第一個n。如果我使用另一種語言(如c/C++),這是一件簡單而容易的事情,但我不知道如何在Haskell中實現它。如何在Haskell中實現帶條件休息的循環
#include <iostream>
long double term(int k) { return 1.0/(k*k+2.0*k); }
int main() {
long double total = 0.0;
for (int k=1;;k++) {
total += term(k);
if (total>=2.99/4.0) {
std::cout << k << std::endl;
break;
}
}
return 0;
}
我用dropWhile和一個有序列表,並拿1拿起第一個。
term k = 1.0/(k*k+2.0*k)
termSum n = sum $ take n $ map term [1..]
main = do
let [(n,val)] = take 1 $ dropWhile (\(a,b)->b <= 2.99/4.0) $ map (\n->(n,termSum n)) [1..]
print n
我知道這太可怕了。什麼是最好的和直觀的方式來寫這個?
回覆: 謝謝你的好評!使用修復功能的一個似乎是在我的機器最快(紅帽6.4 64/80GB存儲器)
方法#0取1和dropWhile(我的最初的實施),使用修復功能
threshold=0.74999 n=99999 time=52.167 sec
方法#1
threshold=0.74999 n=99999 time=0.005 sec
threshold=0.74999999 n=101554197 time=1.077 sec
threshold=0.7499999936263 n=134217004 time=1.407 sec
方法#2向後工作
threshold=0.74999 n=99999 time=0.026 sec
threshold=0.74999999 n=101554197 time=21.523 sec
threshold=0.7499999936263 n=134217004 time=25.247 sec
方法#3勢在必行方式
threshold=0.74999 n=99999 time=0.008 sec
threshold=0.74999999 n=101554197 time=2.460 sec
threshold=0.7499999936263 n=134217004 time=3.254 sec
RERE: 我注意到,無論執行我使用(修復,勢在必行的方式,或遞歸的方式),如果閾值比0.7499999936264大......它永遠不會結束..爲了讓F(N)大於0.7499999936264,我認爲自從![f(n)= \ frac_ {3n^2 + 5n}^{4n^2 + 12n + 8}]之後,我們只需計算高達150,000,000的項。我用Integer代替Int,但它也沒有幫助。如果我將閾值設置爲大於0.7499999936264 ...,是否有任何原因尚未完成?
我可能用明確的遞歸來寫它。我認爲在這裏看起來很乾淨。 –