首页 > 解决方案 > 需要一个函数来验证密码是否强

问题描述

我需要创建一个函数来验证密码是否强大。如果有超过 8 个字符,至少 1 个大写字母、1 个小写字母和 1 个数字。但是我的功能不起作用。有什么问题?

forte :: String -> Bool

forte s = if (length n >= 8) && (isLower s /= 0) && (isUpper s /= 0) && (isDigit s /= 0)
          then True
          else False

标签: haskell

解决方案


欢迎来到stackoverflow。将来,当您说“不起作用”时,请具体说明。复制和粘贴错误消息是一个很好的开始。

对于您的情况,有一些问题。

  1. 没有变量n。我想你的意思s是在length s.
  2. isLower函数对字符而不是字符串(字符列表)进行操作。您应该检查过滤列表的长度 ( length (filter isLower s) /= 0)。isUpper和 也是如此isDigit
  3. 顺便说一句,该if声明是完全不需要的。任何时候你写if expr then True else False它都和只是写一样expr

应用这些建议,我们有:

forte s = (length s >= 8) && (length (filter isLower s) /= 0) && (length (filter isUpper s) /= 0) && (length (filter isDigit s) /= 0)

或使用辅助功能:

forte s = (length s >= 8) && (cnt isLower /= 0) &&
          (cnt isUpper /= 0) && (cnt isDigit /= 0)
  where cnt p = length (filter p s)

但我可能会把它写成(输入但未测试):

forte s = and [ length s >= 8
              , cnt isLower /= 0
              , cnt isUpper /= 0
              , cnt isDigit /= 0]
  where cnt p = length (filter p s)

编辑:啊,我不知道为什么我没有考虑任何而不是计算元素。感谢@lorenzo

forte s = and [ length s >= 8
              , any isLower s
              , any isUpper s
              , any isDigit s]

或者使用 all 和 any,尽管这需要您了解$函数组合 ( .) 的部分应用:

forte s = all ($ s) [ (>= 8) . length
                    , any isLower
                    , any isUpper
                    , any isDigit ]

推荐阅读