[Haskell-beginners] Recursion in monad
adrian.alexander.may at gmail.com
Wed Mar 23 16:46:31 CET 2011
Hi Jedi (why not?)
Thanks for the tips...
> say i = putStrLn $ show i
> This already exist and is called "print" (though its type is more
> general than your signature).
So it is.
> > walk i = randomRIO (0,1) >>= \r -> return (i+r*2-1)
> The >>= ... return is pretty ugly, it would rather be written as :
> > walk i = fmap (\r -> i + r * 2 - 1) $ randomRIO (0,1)
Well, for the time being I like to see exactly what's happening with the
monads. That's why I don't use do. There'll come a day when I already know
and I'll bear it in mind for then.
> > rep n i w s
> Passing say and walk as parameter seems a bit overkill, I seriously
> doubt that you'll ever need this exact structure again, and even then
> passing a single action should be enough :
> > rep n act i
> > | n <= 0 = return ()
> > | otherwise = act i >>= \x -> rep (n-1) act x
But what do I pass for act? walk.say? say>>walk?
> rep may also be written with standard monad operations :
> > rep n act i = foldM (\x _ -> act x) i $ replicate (n-1) ()
Cunning. But it seems a bit round-the-houses to me. I mean, there's no
fundamental reason for that list of nothings; it's just plugging a hole in
haskell. My counter looks naive but at least it's to the point. I guess it's
a matter of taste.
> Lastly it may be that the structure of the program itself,
> particularly the use of randomRIO is suboptimal and a bit ugly, for a
> throwaway program I would probably just use randomRs :
> > main = do
> > g <- newStdGen
> > mapM_ print . tail . scanl (\i r -> i+r*2-1) 50 . take 10 $ randomRs
> (0,1) g
Are there some extra dots in there?
Actually, I can't let the number of random numbers control the number of
iterations because my algorithm asks for random numbers when it feels like
it. You can't predict how many unless you can predict the random numbers. My
main loop is like this:
step (w,i,o) = env o >>= \i' ->
think w i' >>= \o' ->
learn w i i' o o' >>= \w' ->
return (w', i', o')
I tried to tidy that up by factoring out that "remember the last iteration"
business. (It's a Hebbian learning rule.) I figured I could use a comonad
containing the current and previous values of i and o, a function that takes
both and returns the new value, and let cobind shuffle them along. It didn't
work though because I wasn't allowed to say:
instance Comonad (a,a) where ...
instance Comonad ((,) a) where ...
is legal, but I really want to say that both elements of the tuple are the
same, otherwise everything else barfs. Is there some workaround for that?
The compiler seemed to imply that you can only ever have one parameter to a
type in an instance declaration, but that would see rather limiting and
arbitrary. What's the deal here?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners