string - 在 Haskell 中比较两个字符串

标签 string function haskell boolean compare

我遇到了一个相当愚蠢的练习题,它被列为简单,所以我认为我可以做到。前提是医生必须听到病人说“啊”才能做出诊断,但病人的“啊”必须与医生要求的“啊”相符。如果医生问“啊啊”,病人说“啊”,那就不能诊断。 Haskell 程序应该按顺序读取医生和病人 aah,并返回一个 Bool 值来表示是否可以给出诊断。起初我认为它们需要相同,所以这是我的代码:

seeDoctor :: String -> String -> Bool
seeDoctor a b = if a == b then True
                else False

但是,我意识到我没有遵循问题的所有规则,而且事情并不那么简单。患者说“aah”的时间可能比医生长,并返回 True,因此“aah”“aaaah”返回 True,“”“aaah”和“h”“aah”也是如此,但“aaah”“ah”返回 False。但即使医生在 aah 中不包含“h”,患者也必须包含,因此“a”“a”返回 False,但我的代码将返回 True。因此,如果患者说出任何内容,则必须是必要数量的“a”,后跟一个“h”,并且不能有其他字符。你看,一旦我开始尝试建议的测试用例,我就意识到我理解得有多么少。我可以在每个字符串中保留“a”的计数吗?如何检查多余字符?抱歉,这花了一些时间来阅读。感谢您到目前为止。

这是确切的问题:

"When we go to see a doctor, the doctor always asks us to say "aaah". Sometimes, the doctor needs us to say "aaaaaah", but we are only able to say "aaah". In that case, the doctor is unable to diagnose our disease, because the 'a's in our "aaah" are fewer than his or her requirements. Now, write a Haskell function called seeDoctor to judge if the doctor can diagnose us with our "aah". The input of the function consists of two strings. The first string is the "aaaah" the doctor needs and the second string is the "aah" we are able to say. Output "True" if our "aah" meets the requirements of the doctor, and output "False" otherwise. The test should pass with a "True" only when lowercase 'a's and 'h's are used, and each string contains a certain number of 'a's followed by a single 'h'."

最佳答案

既然你正在尝试学习 Haskell,我不会给你一个解决方案,但我会尽力给你足够的提示,使你能够自己组合一个函数。

字符串是列表,因此您可以使用 Data.List 中的普通列表函数。例如,isSubsequenceOf 几乎可以满足您的需要:

Prelude Data.List> isSubsequenceOf "aah" "aaah"
True
Prelude Data.List> isSubsequenceOf "aaaah" "aah"
False

如果我正确解释了问题描述,您可能还应该检查输入字符串中是否只有 ah,并且 h > 是最后一个字符。

为了检查 h 是否是最后一个字符,您可以使用 last 函数:

Prelude Data.List> last "aaaah"
'h'
Prelude Data.List> last "ah"
'h'
Prelude Data.List> last "foo"
'o'

也许您还想检查输入中是否存在恶意字符,如果两个字符串包含 ah< 之外的任何其他字符,则返回 False/...

Prelude Data.List> all (\c -> c == 'a' || c == 'h') "aaah"
True
Prelude Data.List> all (\c -> c == 'a' || c == 'h') "aaah!"
False

但是,对于像 "aha" 这样的字符串,你会怎么做呢?我将把它作为练习:)

关于string - 在 Haskell 中比较两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328106/

相关文章:

c# - 用空字符串替换可变字符串

python - python中的快速、大宽度、非加密字符串散列

c - 使用 strcpy 通过指针运算符将字符串复制到结构的成员

C语言,段错误在哪里?

jquery - .each() 与 for 循环?需要迭代添加字幕

c++ - C++:通过函数传递指针数组的语法

haskell - Haskell 中的 Or 模式

java - Byte[] 数组到字符串 C# 到 Java 无需编码

performance - 如何以空间和时间高效的方式填充 Data.Map

haskell - "<-"do 表示法中的绑定(bind)