-2

I'm looking for a non-recursive implementation of sum of digits (a "cross sum") of a non-negative number like this:

cs :: Int -> Int 
cs n = sum digits_of_n where digits_of_n = [ . | ... ] 

Basically: How does one get a list of digits from a non-negative whole number using list comprehension only?

A cross sum example: The crossum of 157 is 1 + 5 + 7 = 13

The "usual way" would be extracting the digits from a number recursively using modulo and division, and then summing them up like this:

cs :: Int -> Int
cs n = if n == 0 then 0 else n `mod` 10 + cs (n `div` 10)

I have however difficulty expressing this without recursion and with list comprehension, does anyone have ideas regarding this?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • 1
    not sure about you constraints here (Homework?) but I guess `cs :: Int -> [Int]; cs n = [ read [d] | d <- show n ]` does the tick and is using a list comprehension – Random Dev May 21 '21 at 19:20
  • 3
    "I've tried nothing and I'm all out of ideas" doesn't really fly around here. You're going to need to put a good faith effort in before people will be excited about helping you. Read some tutorials, try some things, get the compiler to throw all kinds of errors at you, fix what you can, and come back when you've put in some effort but have a specific thing you're stuck on. – Daniel Wagner May 21 '21 at 20:36
  • Thanks for your comment, I have edited the question, hopefully it makes more sense now. Could someone unlock the question then? – rinteresting May 22 '21 at 16:30

1 Answers1

0
sume n =  foldr (+) 0 [  digitToInt c | c <- show n, isDigit c ]
cealex
  • 173
  • 7