Answer the question
In order to leave comments, you need to log in
I want to compare a piece of code in C and Haskell
Haskell experts, can you show me how the following code, written in C, would look like in Haskell?
defect_N=0;
for(i=N-k+1; i<=N; i++) {
defect_tmp=1;
for(n=1; n<=steps; n++)
for(j=0; j<=N; j++)
defect_tmp-=P_tau_LH[n*(N+1)*(N+1)+i*(N+1)+j];
if(defect_tmp>defect_N)
defect_N=defect_tmp;
printf("%d %lf\n",i,defect_tmp);
}
printf("defect of P_tau_LH=%lf=%e defect_0=%lf, defect_N=%lf\n", max_double (defect_0,defect_N), max_double (defect_0,defect_N), defect_0, defect_N);
Answer the question
In order to leave comments, you need to log in
Well, in general, it would be better if you provided the formulas and not the C program, but if I correctly understood the calculation method, then it will be similar to:
module Main where
import Text.Printf
idef i nn steps =
1 - sum [ n*(n+1)**2 + i*(n+1) + j | j <- [0..nn], n <- [0..steps]]
calcAndPrint i nn steps = do
let res = idef i nn steps
printf "%d %f" i res
return res
defect k nn steps =
maximum [ calcAndPrint i nn steps | i <- [nn- k+1 .. nn]]
main = do
let defect_0 = ...
let defect_N = defect <k> <nn> <steps>
printf "defect of P_tau_LH=%f=%e\n" defect_0
If we take what is called a head-on translation, then it will probably not look very nice (especially in my performance, since I’ll say right away that I’m not a Haskell expert - I’m just interested =)
I tried to throw something in the first approximation (this is just a rough sketch that needs to be finalized to a working version if necessary). It turned out something like this:
N= start = k = defect0 = calcDefectTemp defectStart i = let getInnerPairs steps N = [(i, j) | i <- [1..steps], j <- [0..N]] in let f acc (n, j) = acc - (P_tau_LH !! (n*(N+1)*..... )) in foldl f defectStart (getInnerPairs steps N) calcDefectN defectTemps = maximum(0 : defectTemps) main = do let lst = map (\i -> (i, calcDefectTemp 1.0 i)) [N-k+1..N] mapM (\(idx, def) -> print $ show idx ++ " " ++ show def) lst let defectN = calcDefectN $ map (\(idx, def) -> def) lst print $ "defect of P_tau_LH=" ++ (show $ maximum [defect0, defectN]) ++ ... return()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question