【发布时间】:2021-07-12 00:46:11
【问题描述】:
这是家庭锻炼的一部分,我已经考虑过了,但不了解最后一个障碍。
任务的想法是实现不寻常的子字符串函数,其工作方式如下:
编写一个函数
commonSubstring :: String -> String -> String,给定两个字符串s1和s2,计算s1和s2的公共“子字符串”,如下所示。该函数查找最早的公共字符c(最接近出现在两个序列中的s1或s2的head)。该函数删除两个字符串中的c及其前面的所有字符,将c放入输出字符串中,然后继续。如果最早的常用字符有两个候选,请从
s1中选择一个。
调用此类函数的示例是:
commonSubstring "XabcdefgY" "abcdefgXY" > "XY" commonSubstring "abcdefgXY" "XabcdefgY" > "abcdefgY"
所以,我已经实现了以下递归,这有点工作:
commonSubstring :: String -> String -> String
commonSubstring first_string second_string
| length(second_string)==0=[]
| take 1 first_string ==take 1 second_string=take 1 first_string ++ commonSubstring (tail first_string)(tail second_string)
| otherwise=commonSubstring first_string (tail second_string)
问题是:为什么函数不从匹配的正面对返回最终符号?
commonSubstring "abcdefgXY" "XabcdefgY"
>"abcdefg"
commonSubstring "XabcdefgY" "abcdefgXY"
>"X"
【问题讨论】:
-
您应该使用模式匹配而不是大量的
tail和take 1调用。 -
你能告诉我,这是如何工作的吗? haskell 令人惊讶.. 对我来说很难,尤其是递归。
-
已接受任务,但很想知道替代的、更好的实施方法。