简体   繁体   中英

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?

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' "hey" 2 = "he"

repeat2' "hey" 3 = "hey"

but once I try

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

As it is going to " repeat2' [] _ = undefined";

But I want it to print

repeat2' "hey" 4 = "heyh"

..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 . 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. You need to pass the list along untouched in addition to the one you are traversing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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