【发布时间】:2018-12-18 00:38:16
【问题描述】:
需要制作一个程序来检查给定字符串是否为回文,无论大小写是否不同,它都应该工作,并且应该忽略非字母数字字符,仅使用 Data.char 中的 ord 和 chr 函数和常规函数,没有其他的。我能够创建常规回文检查器:
reverseStr::String->String
reverStr s | s == [] = []
reverseStr (h:t) = reverseStr t ++ [h]
isPalindrome :: String -> Bool
isPalindrome s = s == reverseStr s
我已经开始研究一个函数来规范化大小写:
normalizeCase::String->String
normalizeCase h | h == [] = []
normalizeCase (h) = if ord h > 64 && ord h < 123
then map (chr $ (ord h + 32)) [h]
else h
但我收到以下错误:
• Couldn't match expected type ‘Char -> Char’
with actual type ‘Char’
• In the first argument of ‘map’, namely ‘(chr $ (ord h + 32))’
In the expression: map (chr $ (ord h + 32)) [h]
In the expression:
if ord h > 64 && ord h < 123 then
map (chr $ (ord h + 32)) [h]
else
h
|
6 | then map (chr $ (ord h + 32)) [h] | ^^^^^^^^^^^^^^^^^^
• Couldn't match type ‘Char’ with ‘[Char]’
Expected type: String
Actual type: Char
• In the expression: h
In the expression:
if ord h > 64 && ord h < 123 then
map (chr $ (ord h + 32)) [h]
else
h
In an equation for ‘normalizeCase’:
normalizeCase [h]
= if ord h > 64 && ord h < 123 then
map (chr $ (ord h + 32)) [h]
else
h
|
7 | else h | ^
我对 Haskell 还是很陌生,不知道如何正确实现 ord 或 chr 以便它与这个检查器一起工作,所以任何帮助都将不胜感激!
【问题讨论】:
-
一种方法是规范化大小写,例如,在检查回文之前将所有字符变为大写。作为第一步,你能弄清楚如何使用
ord判断一个字符是否为小写吗?试一试ghci中的函数,看看你是否能注意到一个规律。 -
normalizeCase::String->String normalizeCase h | h == [] = [] normalizeCase [h] = if ord h > 64 && ord h
-
Either 使用
map在列表上“循环”,或手动递归模式匹配解构。 (最好是map。)你似乎试图同时做这两个......
标签: haskell functional-programming palindrome