loops - Haskell - List Error -
i'm trying iterate list , square number , add them together
sumsq (x:xs) = let total = 0 loop length(x:xs) (x:xs) total loop 0 (x:xs) = return () loop n (x:xs) total = let sq = ((x:xs)!!n)^2 total = total + sq loop ((n-1) (x:xs) total) but i'm getting parse error in loop. going wrong?
also there better way this?
first of - miss spaces! significant.
second, forget in let ... in. not use in in do-notation:
sumsq (x:xs) = let total = 0 in loop length(x:xs) (x:xs) total third, not use x , xs form (x:xs) :
sumsq xs = let total = 0 in loop (length xs) xs total and unite our length xsin 1 block. fourth.
fifth, have 3, not 2 arguments loop:
loop 0 xs total = return total sixth, (!!) work 0, use 1, (xs !! (n -1)) right
seventh, don't need use monad, recursion. so, rid return , do
eighth. have infinite recursive total = total + smth
ninth, can't use arguments tuple, so, final working result :
sumsq xs = let total = 0 in loop (length xs) xs total loop 0 xs total = total loop n xs total = loop (n-1) xs total1 sq = (xs !! (n -1)) ^2 total1 = total + sq updated
if talking complexity, not - o(n^2) mentioned in comments : each element seek element. simplify our loop function , rid of n argument:
loop [] total = total loop (x:xs) total = loop xs total1 sq = x ^ 2 total1 = total + sq and our sumsq function write:
sumsq xs = loop xs 0 p.s. implementation easier function sumsq = sum. map (^ 2)
Comments
Post a Comment