简体   繁体   English

Haskell递归与字符列表

[英]Haskell recursion with list of characters

I am studying Haskell and something came up where I am stuck on for few days.. so I am basically trying to recurse through the list of character (String) and once it reaches the end of the string, is there a way for me to recurse through the list from the head again? 我正在研究Haskell,并且出现了几天被卡住的情况..因此,我基本上是在尝试遍历字符列表(字符串),一旦到达字符串末尾,有没有办法让我再次从头到尾遍历列表?

Here is the code that works for recursing through the string once. 这是用于遍历字符串一次的代码。

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

It works for 它适用于

repeat2' "hey" 1 = "h" repeat2'“嘿” 1 =“ h”

repeat2' "hey" 2 = "he" repeat2'“嘿” 2 =“他”

repeat2' "hey" 3 = "hey" repeat2'“嘿” 3 =“嘿”

but once I try 但是一旦我尝试

repeat2' "hey" 4 = "hey*** Exception: Prelude.undefined" repeat2'“ hey” 4 =“ hey ***例外:Prelude.undefined”

As it is going to " repeat2' [] _ = undefined"; 正要进行“ repeat2'[] _ =未定义”;

But I want it to print 但我要打印

repeat2' "hey" 4 = "heyh" repeat2'“嘿” 4 =“嘿”

..So how I do i go back to the head of the string? ..那我该如何回到弦首呢?

Thanks for helping! 感谢您的帮助!

Let me label the equations to refer to them later. 让我标记这些方程式以供以后参考。

   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)

Let's trace the reduction of repeat2' "hey" 4 . 让我们追踪一下repeat2' "hey" 4的减少量。 First I will desugar the string into a list 首先,我将字符串解糖到列表中

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

then the list into its cons cells 然后将列表放入其缺点单元格

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

Now we can begin 现在我们可以开始

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

Thus explaining the output 因此解释输出

"hey***Exception: Prelude.undefined

I hope this helps you understand. 希望这对您有所帮助。

One problem is that in order to cycle the list, you need to keep it around for recursive calls. 一个问题是,为了循环列表,您需要保留它以进行递归调用。 Note that by the time we have printed h, e, y the information to use next is no longer there. 请注意,到我们打印出h,e和y时,下一个要使用的信息不再存在。 You need to pass the list along untouched in addition to the one you are traversing. 除了要遍历的列表之外,还需要沿原样传递列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM