'How can I check the last elements of a string and fix my code?

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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem