简体   繁体   English

验证函数是否是haskell中的回文

[英]Verify if a function is a palindrome in haskell

I've tried to use a function that calculate the reverse of a list.我尝试使用一个计算列表反向的函数。 So I can use it in other function that will be the palindrome function, but always I get an error.所以我可以在其他函数中使用它,这将是回文函数,但总是出现错误。 The first one works.第一个有效。

This is the code:这是代码:

rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]

palindrome :: [a] -> Bool
palindrome [] = True
palindrome (x:xs) = if xs == rev (x:xs) then True else False

I have to mention that I have to do it with that signature: [a] -> Bool我不得不提到我必须用那个签名来做: [a] -> Bool

Someday I will muster the energy to put together a megaquestion to address two common beginner list mistakes: thinking that [x] matches a list of any length, and thinking that any function on lists must have [] and x:xs patterns.有一天我会集中精力整理一个大问题来解决两个常见的初学者列表错误:认为[x]匹配任意长度的列表,以及认为列表中的任何函数都必须具有[]x:xs模式。 This question is an example of the latter.这个问题是后者的一个例子。 When you do the same thing regardless of list length, you don't need multiple patterns!无论列表长度如何,当你做同样的事情时,你不需要多个模式! Just palindrome xs = ... is fine.只是palindrome xs = ...很好。 Try writing your palindrome function again with this in mind;考虑到这一点,尝试再次编写您的palindrome函数; your bug will be fixed as a side effect.您的错误将作为副作用得到修复。

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

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