Taurib
Taurib

Reputation: 461

Get even numbers from string and sum

I need to find all even numbers from String input.

I managed to get all even numbers to list, but I don't understand excactly how can I get sum of those even numbers afterwards.

numbers :: String -> [Int]
numbers [] = []
numbers (l:ls) = if ord l == 48 || ord l == 50 || ord l == 52 || ord l == 54 || ord l == 56
    then (ord l - 48): (numbers ls)
    else (numbers ls)

So the result would be something like: "abc1234" => 6

Upvotes: 2

Views: 857

Answers (2)

karakfa
karakfa

Reputation: 67467

another alternative to write the same

import Data.Char(digitToInt)

sumEvens = sum . map digitToInt . filter (`elem` "2468")

Upvotes: 2

resilva87
resilva87

Reputation: 3465

You're already pretty there. (ord l - 48) extracts the integer value from the string, so you have to accumulate this value. Or sum up the resulting result (which is basically a function)

The basic recursive loop would be:

numbers :: String -> Int -> Int
Given an empty string and accumulated value -> return accumulated value
Given string (l:ls) not empty and accumulated value ->
    if l matches your criteria
           numbers ls (accumulated value + (ord l - 48))
    else 
           numbers ls (solely the accumulated value, as `l` doesn't match criteria)

Upvotes: 2

Related Questions