haskellrecursioninfinite-recursion

How to change the base case so it starts recursion all over?


I am trying to force a recursion to loop infinitely for a project of mine. This is my code up so far:

putStr' :: String -> IO ()
putStr' (a:as) = do putChar a
                    putChar '\n'
                    threadDelay 1000000
                    putStr' as
putStr' []     = putStr'

it throws this error

<interactive>:339:18: error:
    * Couldn't match expected type: IO ()
                  with actual type: String -> IO ()
    * Probable cause: putStr' is applied to too few arguments
      In the expression: putStr'
      In an equation for putStr': putStr' [] = putStr'

I tried this also

putStr' :: String -> IO ()
putStr' (a:as) = do putChar a
                    putChar '\n'
                    threadDelay 1000000
                    putStr' as
putStr' []     = putStr' (a:as)

but to no avail, as it tells me:

<interactive>:297:27: error: Variable not in scope: a :: Char

<interactive>:297:29: error: Variable not in scope: as :: [Char]

I know you are not supposed to do this as it can be dangerous but this is actually what I need for my code to work. Can you help me out? Is this even possible? Should I try a different approach, maybe using guards or something else?


Solution

  • Don't think about looping forever; think about looping over a list which may or may not be infinite, then supply an infinite list.

    putStr' :: String -> IO ()
    putStr'  = traverse_ go . cycle  where
        go x = do putChar x
                  putChar '\n'
                  threadDelay 1000000