如何检查字符串的最后一个元素并修复我的代码?
How can I check the last elements of a string and fix my code?
判断一个字符串是否为标识符,即是否以大写字母或小写字母开头,其他元素均为小写、大写、数字或下划线字符。
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
x
是一个字符串。您使用 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
。您可以使用 (x:xs)
进行模式匹配以获得对头部和尾部的访问,然后使用 all
检查尾部的所有元素是否都满足某个谓词,因此:
identifier :: String -> Bool
identifier (x:xs) = isLetter x && <strong>all … xs</strong>
identifier _ = False
您需要在其中实施 …
部分。
判断一个字符串是否为标识符,即是否以大写字母或小写字母开头,其他元素均为小写、大写、数字或下划线字符。
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
x
是一个字符串。您使用 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
。您可以使用 (x:xs)
进行模式匹配以获得对头部和尾部的访问,然后使用 all
检查尾部的所有元素是否都满足某个谓词,因此:
identifier :: String -> Bool
identifier (x:xs) = isLetter x && <strong>all … xs</strong>
identifier _ = False
您需要在其中实施 …
部分。