Home > Enterprise >  How can i turn single character containting string type to Char in Haskell?
How can i turn single character containting string type to Char in Haskell?

Time:01-06

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

CodePudding user response:

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
  • Related