【问题标题】:How to apply a function to each element of a list of chars如何将函数应用于字符列表的每个元素
【发布时间】:2019-10-09 14:20:15
【问题描述】:

如果输入字符串通过几个条件验证,我想测试它。当我需要将函数应用于列表的其余元素时,我陷入了困境。我应该如何处理这种情况?

我的代码如下:

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]))    |

【问题讨论】:

  • 使用map,但在这里您可能想使用anyall

标签: list function haskell


【解决方案1】:

这里有一些问题。你在这里定义了一个函数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)

【讨论】:

    猜你喜欢
    • 2014-09-24
    • 2021-10-08
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多