Haskell 程序检查输入字符串是否为回文
本教程讨论了如何编写一个程序,在 Haskell 编程语言中检查输入字符串是否为回文。
当一个字符串在反转后仍然与原始字符串完全相同,则称该字符串为回文。例如,字符串“level”就是一个回文,因为它即使反转后也仍然是相同的字符串。
在本教程中,我们将看到:
使用内置函数 reverse 检查字符串是否为回文的程序。
使用递归函数检查字符串是否为回文的程序。
方法 1:使用内置函数检查字符串是否为回文
算法
我们声明一个函数 isPalindrome,该函数返回比较的结果,即一个布尔值。
然后我们声明主函数,其中一个变量 str 初始化为值“kayak”。函数 isPalindrome 被调用,并以初始化的字符串 str 作为参数。函数的输出被加载到变量 status 中。
最后,使用 if 语句检查 status 的值,如果 status 的值为 true,则程序打印该字符串是回文,否则程序打印该字符串不是回文。
示例
-- function declaration
isPalindrome :: [Char]->Bool
-- function definition
isPalindrome str = (str==(reverse str))
main :: IO()
main = do
-- initializing variable str
let str = "kayak"
-- invoking the function isPalindrome
let status = isPalindrome str
-- printing the status
if (status)
then print ("The string " ++ str ++ " is a Palindrome")
else print ("The string " ++ str ++ " is not a Palindrome")
输出
"The string kayak is a Palindrome"
方法 2:使用递归函数检查字符串是否为回文
算法
声明一个函数 StringReverse,该函数返回字符串参数的反转。
声明一个函数 isPalindrome,该函数返回比较的结果,即一个布尔值。
创建主函数并初始化要检查回文的字符串。
使用 isPalindrome 函数和 StringReverse 函数检查两个字符串是否匹配。
打印结果。
示例
-- function declaration
stringReverse :: [Char]->[Char]
-- function definition
-- base case
stringReverse [] = []
stringReverse (ch:str) = (stringReverse str) ++ [ch]
-- function declaration
isPalindrome :: [Char]->Bool
-- function definition
isPalindrome str = (str==(stringReverse str))
main :: IO()
main = do
-- initializing variable str
let str = "kayak"
-- invoking the function isPalindrome
let status = isPalindrome str
-- printing the status
if (status)
then print ("The string " ++ str ++ " is a Palindrome")
else print ("The string " ++ str ++ " is not a Palindrome")
输出
"The string kayak is a Palindrome"
结论
在本教程中,我们讨论了两种在 Haskell 编程语言中实现程序来检查字符串是否为回文的方法。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP