简体   繁体   English

Haskell 递归函数(需要守卫)

[英]Haskell Recursion Function (guards required)

Can someone tell me what's wrong with my implementation of this Haskell palindrome checker?有人可以告诉我这个 Haskell 回文检查器的实现有什么问题吗? Note: Before calling this on the the input string, the string is "cleaned" to get rid of case discrepancies and any non-alphabet characters.注意:在输入字符串上调用它之前,字符串被“清理”以消除大小写差异和任何非字母字符。

checkPalindromeClean :: [Char] -> Bool
checkPalindromeClean inpString
    | length inpString == 0 = True
    | length inpString == 1 = True
    | head inpString == last inpString = checkPalindromeClean (init (tail inpString))
    otherwise False

Here is the (cryptic) error message I am receiving:这是我收到的(神秘的)错误消息:

jdoodle.hs:43:42: error:
    • Couldn't match expected type ‘Bool -> Bool -> Bool’
                  with actual type ‘Bool’
    • The function ‘checkPalindromeClean’
      is applied to three value arguments,
        but its type ‘[Char] -> Bool’ has only one
      In the expression:
        checkPalindromeClean (init (tail inpString)) otherwise False
      In an equation for ‘checkPalindromeClean’:
          checkPalindromeClean inpString
            | length inpString == 0 = True
            | length inpString == 1 = True
            | head inpString == last inpString
            = checkPalindromeClean (init (tail inpString)) otherwise False
   |
43 |     | head inpString == last inpString = checkPalindromeClean (init (tail inpString))
   |                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...

otherwise is a condition too (it is an alias of True ), and therefore should be used as a guard as well, so: otherwise也是一个条件(它是True的别名),因此也应该用作警卫,所以:

checkPalindromeClean :: [Char] -> Bool
checkPalindromeClean inpString
    | length inpString == 0 = True
    | length inpString == 1 = True
    | head inpString == last inpString = checkPalindromeClean (init (tail inpString))
    | otherwise = False

Using length :: [a] -> Int , init :: [a] -> [a] and last :: [a] -> a all run in 𝓞(n) , therefore the algorithm will run in 𝓞(n 2 ) , which is not very efficient.使用length :: [a] -> Intinit :: [a] -> [a]last :: [a] -> a都在𝓞(n)中运行,因此算法将在𝓞(n 2 ) ,这不是很有效。

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

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