如何将函数应用于 haskell 中的列表?

How can I apply to functions to a list in haskell?

我正在尝试编写一个函数来检查给定列表是否为回文。但是,我无法弄清楚如何将函数应用于给定输入。 我的代码如下所示:

isPalindrome :: [a] -> Bool
isPalindrome x
  | head x == last x = True
  | otherwise = isPalindrome tail (init x)

这不起作用,我不知道为什么。

代码的主要问题是逻辑 - 它说“如果头部和尾部匹配,它是一个回文,接受。否则......”真正的测试是“如果头部和尾部不同,拒绝。否则检查中心部分。“

你必须分情况考虑,这个函数可以解决问题:

isPalindrome []       = True   
isPalindrome [x]      = True   
isPalindrome [x,y]    = x == y 
isPalindrome xs       = (head xs) == (last xs) && isPalindrome ((tail . init) xs)

举个例子:

isPalindrome "aabaa"  -->
isPalindrome "aabaa"   = (head "aabaa") == (last "aabaa") && isPalindrome ((tail . init) "aabaa")

下一步)

isPalindrome "aabaa"  = ('a') == ('a') && isPalindrome "aba"

下一步)isPalindrome "aba"

(head "aba") == (last "aba") && isPalindrome ((tail . init) "aba")

下一步 ->

('a') == ('a') && isPalindrome "b")

最后一步 ->

isPalindrome "b"
isPalindrome [x]      = True 

所以我们有表达式:

 ('a') == ('a') && ('a') == ('a') && True --> True