繁体   English   中英

如何将 function 应用于字符列表的每个元素

[英]How to apply a function to each element of a list of chars

如果输入字符串通过几个条件验证,我想测试它。 当我需要将 function 应用于列表元素的 rest 时,我被卡住了。 我应该如何处理这种情况?

我的代码如下所示:

import Data.Char

listLower = ['a'..'z']
listUpper = ['A'..'Z']
listNum = ['0'..'9']
listRes = ["if","then","else","module","import"]


isIdentifierStart :: Char -> Bool
isIdentifierStart x = x `elem` listLower
isIdentifierStart _ = False

isIdentifierPart :: Char -> Bool
isIdentifierPart x = x `elem` listLower || x `elem` listUpper || x `elem` listNum
isIdentifierPart _ = False

isReserved :: String -> Bool
isReserved x = x `elem` listRes
isReserved _ = False

isValid :: String -> Bool
isValid (x:xs) = (isIdentifierStart x) && (isIdentifierPart xs) && (not (isReserved [x]))

我得到的错误信息:

hf4.hs:22:61: error:
    • Couldn't match expected type ‘Char’ with actual type ‘[Char]’
    • In the first argument of ‘isIdentifierPart’, namely ‘xs’
      In the first argument of ‘(&&)’, namely ‘(isIdentifierPart xs)’
      In the second argument of ‘(&&)’, namely
        ‘(isIdentifierPart xs) && (not (isReserved [x]))’
   |
22 | isValid (x:xs) = (isIdentifierStart x) && (isIdentifierPart xs) && (not (isReserved [x]))    |

这里有一些问题。 您在这里定义了一个接受字符串的 function isValid 因此,这意味着x是字符串的第一个字符,而xs是其余字符。

isValid :: String -> Bool
isValid (x:xs) = isIdentifierStart x && all isIdentifierPart xs

您还想在整个字符串上调用isReserved 我们可以通过使用“ as-pattern ”来做到这一点。

isValid :: String -> Bool
isValid xa@(x:xs) = isIdentifierStart x && all isIdentifierPart xs && not (isReserved xa)

最后我们需要在这里覆盖空字符串的情况。 如果一个空字符串被认为是无效的,我们可以这样写:

isValid :: String -> Bool
isValid "" = False
isValid xa@(x:xs) = isIdentifierStart x && all isIdentifierPart xs && not (isReserved xa)

暂无
暂无

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

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