multDigits :: String -> Int
multDigits "" = 1
multDigits str = [product x | x <- str, isDigit x, digitToInt x]
I basically need to get all of the digits from a string and find their product, but can't find much information online on how to use isDigit.
"Hello, m7 name is 9m1" should give the output 63. I am not allowed to use any other functions bar digitToInt.
-
hackage.haskell.org/package/base-4.14.0.0/docs/…willeM_ Van Onsem– willeM_ Van Onsem2020年10月03日 19:01:49 +00:00Commented Oct 3, 2020 at 19:01
-
1@WillemVanOnsem How is that link helpful at all? That function is already in the question.amalloy– amalloy2020年10月03日 19:34:57 +00:00Commented Oct 3, 2020 at 19:34
-
seems fair to me as a response to "[I] can't find much information online on how to use isDigit."Robin Zigmond– Robin Zigmond2020年10月03日 19:44:41 +00:00Commented Oct 3, 2020 at 19:44
-
I meant within string comprehension, sorry about that.Robert Lutino– Robert Lutino2020年10月03日 22:21:22 +00:00Commented Oct 3, 2020 at 22:21
1 Answer 1
digitToInt x
will not work, since that is a filter in the list comprehension, and this thus means that digitToInt x
should return a Bool
. Even if somehow that would work, it would not do much, since it would convert it to an Int
, and then you ignore the result.
You should put the digitToInt
in the "yield" part of the list comprehension, so:
[digitToInt x | x <- str, isDigit x]
now we have a list of Int
s, but this will not calculate the product
, you can not put the product :: (Foldable f, Num a) => f a -> a
function in the yield part, since then you calculate the product per item, but you can not calculate the product
of a simple Int
. You thus calculate the product over the entire list, so:
multDigits :: String -> Int
multDigits str = product [digitToInt x | x <- str, isDigit x]
You can also make use of map :: (a -> b) -> [a] -> [b]
and filter :: (a -> Bool) -> [a] -> [a]
, instead of using list comprehension, so:
multDigits :: String -> Int
multDigits = product . map digitToInt . filter isDigit