如何解决如何将函数应用于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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。