[Haskell-cafe] Recursion

Bryan Burgers bryan.burgers at gmail.com
Tue Mar 6 11:52:56 EST 2007


On 3/6/07, Dave at haskell.org <Dave at haskell.org> wrote:
> Does the following code increase the level of recursion
> once for each input line or is the recursive construct
> converted to an iteration?
>
> Thanks,
> Dave Feustel
>
> main :: IO ()
> main = do
>   line <- getLine
>   processIt line
>   main
>
> processIt   :: String -> IO ()
> processIt s = do
>   print (length s)

Dave,

I would imagine it does not, but I will let somebody more
knowledgeable tell you for sure. My thought, though, is that if this
is your whole code and not a simplified version (eg, one that
terminates on certain input), then you could consider using the
Prelude's 'interact'[1] function, which performs a transformation on
standard input. In your case, the code would simplify to:

main = interact (unlines . map (show . length) . lines)

The unlines/lines combo breaks up the whole input into a list of lines
of input, and the (show . length) is the heart of your 'processIt'
function.

Alternately, you could also use something like:

main = getContents >>= mapM_ processIt . lines

Which takes everything from standard in, splits it up into lines, and
then performs processIt for each line.

[1] http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Ainteract

Bryan


More information about the Haskell-Cafe mailing list