如何更改基本情况以使其重新开始递归?

问题描述 投票:0回答:1

我正在尝试强制递归为我的项目无限循环。 这是我到目前为止的代码:

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

它抛出这个错误

<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'

我也尝试过这个

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

但无济于事,它告诉我:

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

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

我知道你不应该这样做,因为它可能很危险,但这实际上是我的代码正常工作所需要的。你能帮我吗?这可能吗?我应该尝试不同的方法,也许使用警卫或其他什么?

haskell recursion infinite-recursion
1个回答
0
投票

不要考虑永远循环;考虑循环一个可能是无限的列表,也可能不是无限的,然后提供一个无限列表。

putStr' :: String -> IO ()
putStr'  = traverse go . cycle  where
    go x = do putChar x
              putChar '\n'
              threadDelay 1000000
© www.soinside.com 2019 - 2024. All rights reserved.