Haskell 带字符列表的递归

Haskell recursion with list of characters

我正在学习 Haskell 并且出现了一些问题,我坚持了几天..所以我基本上是在尝试递归字符列表(字符串),一旦它到达字符串,有没有办法让我再次从头部递归列表?

这是用于递归一次字符串的代码。

repeat2' :: [Char] -> Int -> [Char]
repeat2' [] _ = undefined
repeat2' (x:xs) 1 = [x]
repeat2' (x:xs) k
    | (k > 0) = x: repeat2' xs(k-1)

适用于

repeat2' "hey" 1 = "h"

repeat2' "hey" 2 = "he"

repeat2' "hey" 3 = "hey"

但是一旦我尝试

repeat2' "hey" 4 = "hey*** Exception: Prelude.undefined"

因为它将要“repeat2'[] _ = undefined”;

但是我想要打印出来

repeat2' "hey" 4 = "heyh"

..那么我该如何回到字符串的开头?

感谢您的帮助!

让我标记方程式以供稍后参考。

   repeat2' :: [Char] -> Int -> [Char]
1) repeat2' [] _ = undefined
2) repeat2' (x:xs) 1 = [x]
   repeat2' (x:xs) k
3)     | (k > 0) = x: repeat2' xs(k-1)

让我们追踪一下 repeat2' "hey" 4 的减少情况。首先,我会将字符串脱糖到列表中

repeat2' ['h', 'e', 'y'] 4

然后将列表放入其缺点单元格

repeat2' ('h':'e':'y':[]) 4

现在我们可以开始了

repeat2' ('h':'e':'y':[]) 4
-- equation 3 applies, x = 'h', xs = 'e':'y':[], k = 4
'h' : repeat2' ('e':'y':[]) 3
-- the first element of the result is known now, so it is printed by the repl
-- equation 3 applies ot the remainder
'h' : 'e' : repeat2' ('y':[]) 2
-- e is now known and printed
-- equation 3 applies
'h' : 'e' : 'y' : repeat2' [] 1 
-- y is known and printed
-- equation 1 applies
'h' : 'e' : 'y' : undefined
-- the repl errors out because of undefined

从而解释输出

"hey***Exception: Prelude.undefined

希望对您有所帮助。

一个问题是,为了循环列表,您需要保留它以供递归调用。请注意,当我们打印 h、e、y 时,接下来要使用的信息已不存在。除了您正在遍历的列表之外,您还需要将列表原封不动地传递。