[Haskell-cafe] Recursion
Jefferson Heard
jeff at renci.org
Tue Mar 6 13:50:09 EST 2007
Bryan,
The code here does not take advantage of laziness, which is probably what you
want to do, as it is much cleaner to look at and more Haskell like. In
answer to your question it is tail recursive, and strict, which means that in
some compilers, with some optimization flags (i.e. GHC) you will get an
iteration instead of a recursion, but consider instead this:
main = do
input = readFile stdin
let r = map processit (lines input)
putStrLn (unlines s)
For more details, see:
http://blogs.nubgames.com/code/?p=22
On Tuesday 06 March 2007 11:52, Bryan Burgers wrote:
> 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%3Aint
>eract
>
> Bryan
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list