![](/img/trans.png)
[英]Converting a string of characters into a list with a set layout in 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'“嘿” 1 =“ h”
repeat2'“嘿” 2 =“他”
repeat2'“嘿” 3 =“嘿”
但是一旦我尝试
repeat2'“ hey” 4 =“ hey ***例外:Prelude.undefined”
正要进行“ repeat2'[] _ =未定义”;
但我要打印
repeat2'“嘿” 4 =“嘿”
..那我该如何回到弦首呢?
感谢您的帮助!
让我标记这些方程式以供以后参考。
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时,下一个要使用的信息不再存在。 除了要遍历的列表之外,还需要沿原样传递列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.