P
P
PQR2013-09-28 17:10:34
Haskell
PQR, 2013-09-28 17:10:34

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

2 answer(s)
S
shedward, 2013-09-29
@shedward

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

I haven't written much in Haskell, so maybe there is a better way.

T
tvolf, 2013-09-28
@tvolf

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()

In general, as far as I understand, for functional languages ​​it is often necessary to build on the input conditions in order to form the correct algorithm for solving the problem, since the “literal implementation” of the imperative code does not give the best results (to put it mildly =).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question