I know the function:
numbers xs = filter (\x -> x `elem` [0..9]) xs
Example: numbers "123Text321"
-> 123321
I don't want to filter all the integers from the String, only the first set ("123"
).
What would a function need that only takes the first Integers from a string it sees and as soon as it comes to a char it returns the Integers it has found.
Another example: numbers "b123w321"
-> should return 123
.
CodePudding user response:
You can use takeWhile
combined with isDigit
:
import Data.List(takeWhile)
import Data.Char(isDigit)
numbers = takeWhile isDigit
Your attempt didn't work, because filter
by its definition traverses the whole list and is unaware of the progress over the traversal (it won't tell that it is supposed to stop after seeing a non-digit).
The other issue is that integers are not chars in Haskell, so you should rather look for '0'..'9'
instead of 0..9
.