Field updates in a state monad

Hello list, still playing with monads and states, I have the following question: Given: import Control.Monad.State.Lazy data MyData = MyData { content :: String } foobar :: State MyData String foobar = do gets content Ok, that looks nice and tidy. But: foobar2 :: State MyData () foobar2 = do modify $ \x -> x { content = "hello haskell"} ...looks not so nice. Exists there a way to write this cleaner without writing countless "set_xyz" helper functions? Michael

2008/1/10, Lutz Donnerhacke
* Michael Roth wrote:
Exists there a way to write this cleaner without writing countless "set_xyz" helper functions?
The syntactic sugar for record modifications is simply that: sugar. You might write your own modifier functions: set_bla x y = x { bla = y }
That seems to be exactly what Michael search to avoid. And I don't see any way to do that with the haskell records. Some extension of records may have first-class label though. A pretty interesting alternative could be HList, it has first-class label and a bunch of other good stuff. I never used it though, so I don't know how it affects the performances, if someone could give his experience with it ? -- Jedaï

On Jan 11, 2008 2:01 AM, Michael Roth
Hello list, Exists there a way to write this cleaner without writing countless "set_xyz" helper functions?
The "set_xyz" methods have to be written, but that doesn't mean *you* have to write them. You can use Template Haskell to automatically derive setter functions for you. Writing the TH derivations is a little fiddly, but luckily others have already encountered the same problem. These blog posts can point you to a few implementations: http://luqui.org/blog/archives/2007/08/05/haskell-state-accessors-second-att... (http://tinyurl.com/2ve2zw) http://twan.home.fmf.nl/blog/haskell/overloading-functional-references.detai... (http://tinyurl.com/2ustba) In particular, take a look at Luke's code, because it also contains helper functions for combining these getters and setters with MonadState. Stuart

On Thu, 10 Jan 2008, Michael Roth wrote:
Hello list,
still playing with monads and states, I have the following question:
Given:
import Control.Monad.State.Lazy
data MyData = MyData { content :: String }
foobar :: State MyData String foobar = do gets content
Ok, that looks nice and tidy. But:
foobar2 :: State MyData () foobar2 = do modify $ \x -> x { content = "hello haskell"}
...looks not so nice.
Exists there a way to write this cleaner without writing countless "set_xyz" helper functions?
participants (5)
-
Chaddaï Fouché
-
Henning Thielemann
-
Lutz Donnerhacke
-
Michael Roth
-
Stuart Cook