I’m brand new to haskell and am working through some tutorial problems for a functional programming course I am taking. There is one problem that I am completely stumped on.
Define a function that returns whether a given string contains all numerical values or not (i.e. “123” => True, “1a3” => False). The function must use a list comprehension.
It’s this last part that is killing me. It’s easy to write without a list comprehension. It’s also easy to write a list comprehension with a predicate to ensure that you only put numerical chars into a new list.
isNum = [ x | x <- xs, x `elem` ['0'..'9'] ]
However I’m not sure how to then compare the new list to the original list to check for equality since this is the entire function definition.
Is this homework?
Since the list comprehension will only include characters that are numerals, if there are any non-numeric elements, the resulting list will be shorter.
Another approach is to put
isNum xs = [ elem x ['0'..'9'] | x <- xs ]. Then you have a list of Boolean values telling you whether each character was a numeral. You can use a Prelude function to tell you whether all the values wereTrueor not.EDIT: more efficiently, there is also a Prelude function that can tell you whether any of the elements was
False, indicating a non-numeric element.