Decide whether a string is an identifier, that is, whether it starts with an uppercase or lowercase letter and all other elements are all lowercase, uppercase, digit, or underscore characters.
isunderscore :: Char -> Bool
isunderscore a
|a == '_' = True
|otherwise = False
identifier :: String -> Bool
identifier (x:xs) = isLetter x && ( all isLetter xs || all isunderscore xs || all isDigit xs )
identifier _ = False
CodePudding user response:
x
is a string. You use last :: [a] -> a
to obtain the last element. But here you need to check if all remaining elements satisfy a certain predicate. This means that you can work with all :: Foldable f => (a -> Bool) -> f a -> Bool
. You can pattern match with (x:xs)
to obtain access to the head and the tail, and then check with all
if all elements of the tail satisfy a certain predicate, so:
identifier :: String -> Bool
identifier (x:xs) = isLetter x && all … xs
identifier _ = False
where you need to implement the …
part.