functional programming - Encapsulating a list of functions in haskell in a single one -


someone said might not "getting" how proper code in haskell. must totally right, feel haskell code simpler functions ugly (at least compared oop code in "standard" language such java or c++):

mev = matrixexpvalues 5 4 3 cs = canonicalst 4 3  cs_t1 = map (foldl (++) "") (map (map show) cs) cs_t2 = map (++ ":") cs_t1 mev_t1 = intxxstostringxxs mev mev_t2 = map (map (++ "\t")) mev_t1 mev_t3 = map (foldl (++) "") mev_t2 res1 = zipwith (++) (map (++ "\t") cs_t2) mev_t3 res2 = map (++ "\n") res1 final_result = foldl (++) "" res2 

with mev , cs of:

*main> mev [[2,-2,-2,-6],[4,2,0,-2],[2,2,4,4],[6,4,2,2],[6,4,2,6]] *main> cs [[0,0,4],[0,1,3],[0,2,2],[1,1,2]] 

(those values hand typed, need work arbitrary mev , cs!) have 2d matrix applied sequence of operations until got desired result.

this works, i'd encapsulate logic in single function (let's call matrix_transf). current code tied matrixexpvalues , canonicalst return, , i'd have like

matrix_transf mev cs =      ...all transformations     ...until final_result 

all kind of criticism welcome (i need can improve!) believe haskell coders approach in total different way , looking know!

first going show isn't optimal (for instance kennytm's code looks whole lot better.) show how code if change intxxstostringxxs map (map show) , continuously apply rule :

  • map f (map g xs) ==> map (f.g) xs

while inlining definitions when possible. also, make better, have applied these rules:

  • foldl (++) "" ==> concat
  • concat (map f xs) ==> concatmap f xs
  • concatmap (++ "\n") ==> unlines

afer quite lof of rewriting, give this:

cs_t3  = map ((++ ":\t") . concatmap show) cs  mev_t3 = map (concatmap ((++"\t") . show)) mev  final_result = unlines (zipwith (++) cs_t3 mev_t3)  

i know doesn't better, shouldn't take long figure out can write matrix_transf this:

matrix_transf mev cs = unlines (zipwith (++) (starts cs) (endings mev))  starts  = map ((++ ":\t") . (concatmap show))  endings = map (concatmap ((++"\t") . show))      

or this:

matrix_transf mev cs = unlines . zipwith (++) starts $ endings     starts  = map ((++ ":\t") . (concatmap show)) cs            endings = map (concatmap ((++"\t") . show)) mev  

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -