George312
George312

Reputation: 27

How to sum only the odd indexed digits in Haskell?

I have an input integer: 23415423

My program can split it into an array and sum them, but i only need the odd ones.
I have tried ?^ element but not working.

lsum :: Num a => [a] -> a
lsum [] = 0
lsum (h:t) = h + sum t

Upvotes: 0

Views: 807

Answers (2)

gabesoft
gabesoft

Reputation: 1228

You could add the indexes, filter only the ones you need, and then sum.

lsum xs = sum $ map fst $ filter (odd . snd) $ zip xs [1..]

Upvotes: 1

jakubdaniel
jakubdaniel

Reputation: 2223

First, the problem with what you try, is that you simply call sum on the rest of the digits, this is not your lsum so how do you expect it to skip elements? So you probably wanted to put lsum there instead and make a recursive call.

Now you would like to take control over your recursion.

If you insist on walking over a list of digits, you could reverse it, and then make your recursion skip elements (alternatively, you would have to recurse to the end of the list and start eating it from there, in which case it would get messier to recognize which elements to include in the sum):

lsum = lsum' . reverse where
    lsum' :: Num a => [a] -> a
    lsum' [] = 0
    lsum' [_] = 0
    lsum' (_ : odd : tail) = odd + lsum' tail

or you could alternate between two consumers of the list

    lsum' :: Num a => [a] -> a
    lsum' [] = 0
    lsum' (_ : tail) = lsum'' tail

    lsum'' :: Num a => [a] -> a
    lsum'' [] = 0
    lsum'' (odd : tail) = odd + lsum' tail

of course there are many other ways, but I guess this might inspire you to search for a better solution yourself, as it seems like a school assignment.

Upvotes: 2

Related Questions