简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM