1
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.

asked Oct 3, 2020 at 18:56
4
  • hackage.haskell.org/package/base-4.14.0.0/docs/… Commented Oct 3, 2020 at 19:01
  • 1
    @WillemVanOnsem How is that link helpful at all? That function is already in the question. Commented 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." Commented Oct 3, 2020 at 19:44
  • I meant within string comprehension, sorry about that. Commented Oct 3, 2020 at 22:21

1 Answer 1

2

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 Ints, 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
answered Oct 3, 2020 at 19:34
Sign up to request clarification or add additional context in comments.

1 Comment

That you very much, you gave me a lot of useful key words to look up, and a very good explanation!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.