2

I'm trying to write a function that reads from a String in Haskell, if the String has a number, it should return True. This is what I currently have

hasNumber :: String -> Bool
hasNumber n = any number

I have tried lots of functions in the second line but it doesn't seem to work, can anyone help me? Thank you!

2
  • Well, obviously you need to insert a 'real' function for number (I think you mean "digit" here?). What have you tried for that? Commented Mar 7, 2014 at 20:56
  • Where you trying to use number :: Integral i => Int -> GenParser tok st Char -> GenParser tok st i from Text.ParserCombinators.Parsec.Number, or what's that number in your question? Commented Mar 7, 2014 at 20:57

2 Answers 2

2

Assuming you want to check whether your string is an natural number it boils down to

import Data.Char (isDigit)

hasNumber :: String -> Bool
hasNumber = all isDigit

If you don't want to use Data.Char (or aren't allowed if this is an assignment), you can use

isDigit = (`elem` ['0'..'9'])

If you want to check whether the number is integral, you have to check whether the string starts with a '-', and if it does, whether the rest of the string is a natural number:

isIntegral :: String -> Bool
isIntegral ('-':[]) = False        -- string is "-", which isn't a number
isIntegral ('-':xs) = hasNumber xs -- string is "-....", so we check "...."
isIntegral x        = hasNumber x  -- string doesn't start with '-'
Sign up to request clarification or add additional context in comments.

2 Comments

hasNumber "-37" == False. Maybe you meant natural number, not integral number?
@kqr: Yes. Added isIntegral for completion.
2

Should refine what you want by "number", but supposing you want to simply read one of the Haksell numeric types formatted as a string in the way Haskell prints them, then you can use the readMaybe function.

import Text.Read

hasNumber :: String -> Bool
hasNumber x = isJust ( readMaybe x :: Maybe Int )

If you want to read a different numeric type than change the type annotation to Maybe Double, Maybe Integer or whatever you want.

If you need to parse a variety of number formats that differ from the way that Haskell shows them by default, then use a parser library like Parsec.

Comments