[Haskell-cafe] foldl and space problems
Andrew Pimlott
andrew at pimlott.net
Mon Jun 13 14:00:23 EDT 2005
On Mon, Jun 13, 2005 at 03:29:21PM +0200, Gracjan Polak wrote:
> Bernard Pope wrote:
> >Perhaps you could post the definition of the state type? Or even better,
> >a small example of code that runs badly.
>
> I still don't know where old code had problems, but after rewriting
> everything it seems to run smoothly now :) Thanks for all ideas, btw.
>
> I "invented" something like this:
>
> type RestAndState = (MyState -> [MyData]) -> MyState -> [MyData]
>
> this is the type of funtions that take current state and continuation as
> parameters. Example:
>
> putValues v1 v2 v3 rest state =
> [v1,v2,v3] ++ rest state
>
> there is a bit of syntactic ugliness when state chages:
>
> putValueEx v1 rest state =
> let newstate = state { ... } in
> [v1] ++ rest nstate
>
> good thing is that function can be composed quite easily with ($):
>
> putV v1 v2 v3 v4 rest = -- state skipped here :)
> putValue v1 v2 v3 $
> putValueEx v4 rest
>
>
> It works as I want it to. But I have strange feeling that there must be
> a better way to "compose" foldr and state... Does anybody have any idea
> how to put monad into this?
I haven't followed the thread from the beginning, but here is one way of
expressing your examples, using State and foldr1:
putValues :: a -> a -> a -> State s ([a] -> [a])
putValues v1 v2 v3 = return ([v1,v2,v3] ++)
putValueEx :: a -> State s ([a] -> [a])
putValueEx v1 = do modify (\s -> undefined)
return (v1 :)
putV :: a -> a -> a -> a -> State s ([a] -> [a])
putV v1 v2 v3 v4 = foldr1 (liftM2 (.))
[putValues v1 v2 v3, putValueEx v4]
test = evalState (putV 1 2 3 4) undefined []
I'm not sure exactly what you're trying to accomplish, but maybe this
will give you some ideas.
Andrew
More information about the Haskell-Cafe
mailing list