[Haskell] recursion patterns?
David Virebayre
dav.vire+haskell at gmail.com
Tue May 21 12:09:37 CEST 2013
2013/5/15 7stud <7stud at excite.com>
> >The first solution works for infinite lists and the second one does not.
> I don't see how that's possible. Both traversals seem to be limited by
n, and therefore they do not have to touch the end of the list. In any
case, it would seem to me that the *first* solution would be the one that
wouldn't work on an infinite list. Can you explain?
The first version returns a tuple with a list and a generator.
If you want the first value, you will evaluate the list constructor ":",
then evaluate "value", then "random gen" and you have the value.
For each new value you need, you will evaluate resteOfList, so will call
finiteRandoms recursively just once.
To better see it, you can modify it by removing the n : (warning, this
function doesn't make sense, I'll explain why afterwards)
finiteRandoms' :: (RandomGen g, Random a) => g -> ([a], g)
finiteRandoms' gen =
let (value, newGen) = random gen
(restOfList, finalGen) = finiteRandoms' newGen
in (value:restOfList, finalGen)
and then you could try it like this :
l' :: [Int]
(l',f') = finiteRandoms' (mkStdGen 1)
in ghci, if you type l', it will run in an infinite loop. But it you type
take 10 l', it works.
A warning though, this function (that was just for learning purpose) has a
huge flaw: it returns the final generator, but you can't use it. If you
try, it will run into an infinite loop.
Now In your version, the first thing the function does is call itself
recursively. So before you can get a result, you will do all the recursive
calls until the last one.
David.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell/attachments/20130521/386c3555/attachment.htm>
More information about the Haskell
mailing list