简体   繁体   English

如何在Haskell中检查字符串的每个字符

[英]How to check for each char of a string in Haskell

I've got a homework for a function that checks if a username is valid or not. 我有一个用于检查用户名是否有效的函数的功课。 Allowed chars are underscore, letters, and digits. 允许的字符为下划线,字母和数字。 I'm not allowed to use indexing (!!) and Length 我不允许使用索引(!!)和长度

My code so far: 到目前为止,我的代码:

isValid' :: Char -> Bool
isValid' x
     | x == '_'    = True
     | x `elem` ['0'..'9'] = True
     | x `elem` ['a'..'z'] = True
     | x `elem` ['A'..'Z'] = True
     | otherwise           = False

isValidUsername :: [Char] -> Bool
isValidUsername x
     | map isValid' x = True
     | otherwise     = False

I want to run my isValid function on all chars of the string i put in isValidUsername. 我想在我放入isValidUsername的字符串的所有字符上运行isValid函数。 For example: 例如:

isValidUsername "MyUsername_123" should return True isValidUsername "MyUsername_123"应该返回True

isValidUsername "not@v@lidusern@me* *2" should return False isValidUsername "not@v@lidusern@me* *2"应该返回False

I just can't figure out how to run through all the chars of my string. 我只是想不出如何遍历字符串的所有字符。

Well if you want all the elements to satisfy the isValid' function, you can use the all :: (a -> Bool) -> [a] -> Bool function, so you can rewrite your function to: 好吧,如果您希望所有元素都满足isValid'函数,则可以使用all :: (a -> Bool) -> [a] -> Bool函数,因此可以将函数重写为:

isValidUsername :: [Char] -> Bool
isValidUsername x = all isValid' x

or even shorter: 甚至更短:

isValidUsername :: [Char] -> Bool
isValidUsername = all isValid'

Note that here it means that the empty string "" is a valid username as well, since for an empty string, all characters (there are no characters) are in the alphanumerical range. 请注意,这里的意思是空字符串 ""也是有效的用户名,因为对于空字符串,所有字符(没有字符)都在字母数字范围内。

Okay, i figured it out: 好的,我知道了:

isValidUsername :: [Char] -> Bool
isValidUsername x
     | False `elem` (map isValid x) = False
     | otherwise                    = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM