zauahiri
zauahiri

Reputation: 15

Haskell manipulating elements of a list

So lets say i have a certain string and i want to check the elements of the string, whether they are numbers or characters. Each number has to be replaced with the number 1 and each character with the number 2 and at the end it has to be shown the final result when you sum all numbers. Example: function "123abc" has to give a result 9

I've already come up with a solution using lists comprehensions and pattern matching, but i need to be able to give a solution without using them, meaning only elem,head,tail,reverse,map,sum etc. All has to be 1 function, now a few combined as one.

Upvotes: 0

Views: 138

Answers (1)

Redu
Redu

Reputation: 26191

You may do as follows;

import Data.Char (isDigit)
import Data.Bool (bool)

getsum :: String -> Int
getsum = sum . map (bool 2 1 . isDigit)

*Main> getsum "1234abc"
10

Upvotes: 6

Related Questions