2

I am new to Haskell. I have string containing single character for example "A" or "3". I want to turn it into character to check if it is a digit with isDigit :: Char -> Bool function. How can I turn that the string into character?

I tried:

isDigit head x
-- and
isDigit take 1 x

witch gave me errors: Variable not in scope: isDigit :: ([a0] -> a0) -> String -> Bool and Variable not in scope: isDigit :: (Int -> [a0] -> [a0]) -> t0 -> String -> Bool

2
  • 1
    isDigit head x calls isDigit with two arguments (head and x). You probably want isDigit (head x) instead. The expression isDigit take 1 x suffers from the same issue (but won't work anyway, since take returns a list/string, not a single char). Commented Jan 5, 2023 at 23:17
  • Consider using something like all isDigit to be robust to mistakenly calling with strings of other lengths. Or, if this is part of a validation pass, something like singleDigit :: String -> Maybe Int; singleDigit [x] | isDigit x = Just (digitToInt x); singleDigit _ = Nothing, which returns a failed validation for other lengths, and converts to a more suitable internal representation when validation passes. Commented Jan 6, 2023 at 15:36

1 Answer 1

3

The function isDigit is defined in Data.Char, so you'll need to import that module. Also, as noted in the comment, the expression isDigit head x will try to call isDigit with two arguments, head, and x. You want to evaluate head x and pass that single argument to isDigit, so you'll need to write isDigit (head x). The following program should work:

import Data.Char

string1 = "A"
string2 = "3"

main = do
  print $ isDigit (head string1)
  print $ isDigit (head string2)

or if you are trying to evaluate this interactively in GHCi, use:

ghci> import Data.Char
ghci> isDigit (head "A")
False
ghci> isDigit (head "3")
True
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.