我想要一个带文本并改变一些单词的程序,特别是它应该写" Leonardo"每当它读到" Chiara"反之亦然。这是我的代码:
changeText [] = []
changeText (x:xs)
| x == "C" = isChiara x xs
| x == "L" = isLeo x xs
| otherwise = x ++ changeText x
isChiara x xs
| nome == "hiara" = "Leonardo" ++ changeText (drop 5 xs)
| otherwise = x ++ changeText xs
where nome = take 5 xs
isLeo x xs
| nome == "eonardo" = "Chiara" ++ changeText (drop 7 xs)
| otherwise = x ++ changeText xs
where nome = take 7 xs
然而,当我尝试运行它时,我收到此错误:
main.hs:10:1: error:
Couldn't match type `[Char]' with `Char'
Expected type: [Char] -> [Char]
Actual type: [[Char]] -> [Char]
main.hs:17:13: error:
* Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
Actual type: [Char]
* In the second argument of `(==)', namely `"hiara"'
In the expression: nome == "hiara"
In a stmt of a pattern guard for
an equation for `isChiara':
nome == "hiara"
main.hs:17:49: error:
* Couldn't match type `[Char]' with `Char'
Expected type: [Char]
Actual type: [[Char]]
* In the first argument of `changeText', namely `(drop 5 xs)'
In the second argument of `(++)', namely `changeText (drop 5 xs)'
In the expression: "Leonardo" ++ changeText (drop 5 xs)
main.hs:18:33: error:
* Couldn't match type `[Char]' with `Char'
Expected type: [Char]
Actual type: [[Char]]
* In the first argument of `changeText', namely `xs'
In the second argument of `(++)', namely `changeText xs'
In the expression: x ++ changeText xs
main.hs:22:13: error:
* Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
Actual type: [Char]
* In the second argument of `(==)', namely `"eonardo"'
In the expression: nome == "eonardo"
In a stmt of a pattern guard for
an equation for `isLeo':
nome == "eonardo"
main.hs:22:49: error:
* Couldn't match type `[Char]' with `Char'
Expected type: [Char]
Actual type: [[Char]]
* In the first argument of `changeText', namely `(drop 7 xs)'
In the second argument of `(++)', namely `changeText (drop 7 xs)'
In the expression: "Chiara" ++ changeText (drop 7 xs)
main.hs:23:33: error:
* Couldn't match type `[Char]' with `Char'
Expected type: [Char]
Actual type: [[Char]]
* In the first argument of `changeText', namely `xs'
In the second argument of `(++)', namely `changeText xs'
In the expression: x ++ changeText xs
Failed, modules loaded: none.
出了什么问题?我完全是Haskell的新手,我试图寻找类似问题的答案,但我真的很难理解发生了什么。
答案 0 :(得分:5)
Haskell中的字符串是Char列表; Haskell将其类型表示为[Char]
。
如果你写'C'
,那么Haskell会把它解释为Char C
如果你写"C"
,那么Haskell会将其解释为单字符串“C”
Haskell对使用正确的类型很迂腐。
为了给你更具体的解决方案:
问题起源于第一部分。
changeText (x:xs)
| x == "C" = isChiara x xs
| x == "L" = isLeo x xs
| otherwise = x ++ changeText xs
x
是一个Char,但是你将它与"C"
或"L"
进行比较 - 哪个Haskell将其解释为1个字符的字符串。
成功:
changeText (x:xs)
| x == 'C' = isChiara x xs
| x == 'L' = isLeo x xs
| otherwise = x ++ changeText xs
错误信息应该消失。
答案 1 :(得分:3)
既然你已经解决了这个问题,那么让我展示一个相当短的替代方案
people_count = int(input("Enter how many names you wish to have, min 0, max 20: "))
for l in range(people_count):
generate_random_names = random.choice(names)
print (generate_random_names)