
Hi. I have definitions like data MyData = MyData { a :: A, b :: B, c :: C, d :: D, ... z :: Z } makeMyData :: A -> B -> MyData makeMyData a' b' = MyData { a = a', b = b', c = default_c, ... z = default_z } The goal is to use it like myData1 = set_x x' . set_m m' . set_c c' $ makeMyData my_a my_b myData2 = set_z z' . $ makeMyData my_a my_b But. Writing set_* functions is a problem - MyData is loong and things like set_d :: D -> MyData -> MyData set_d val struct = struct{d=val} will form that boilerplate. Is there any _right_ way of doing it? myData3 = (makeMyData my_a my_b) {x=x', z=z'} approach is not working.. -- Thanks, Sergey

On Sun, Mar 14, 2010 at 04:54:05PM +0300, Sergey Mironov wrote:
Hi. I have definitions like
data MyData = MyData { a :: A, b :: B, c :: C, d :: D, ... z :: Z }
...
will form that boilerplate. Is there any _right_ way of doing it?
Unfortunately there is no better way of doing it. _However_, there are several packages which can generate all this boilerplate code for you! Check out fclabels [1] or data-accessor [2]. -Brent [1] http://hackage.haskell.org/package/fclabels [2] http://hackage.haskell.org/package/data%2Daccessor

Using the record update syntax might make it a little nicer, also the record syntax already provides getters and setters. data MyData = MyData { a :: Int, b :: Int, c :: Int } deriving (Show) def = MyData 1 2 3 -- or -- def = MyData {a = 1, b = 2, c = 3} makeMyData :: Int -> Int -> MyData makeMyData a' b' = def { a = a', b = b'} myData1 = (makeMyData 9 10) {a = 1} myData2 = (makeMyData 11 12) {c = 12} With syntax highlighting: http://haskell.pastebin.com/LxtLZCtL HTH, Rahul

2010/3/14 Rahul Kapoor
Using the record update syntax might make it a little nicer, also the record syntax already provides getters and setters.
data MyData = MyData { a :: Int, b :: Int, c :: Int } deriving (Show)
def = MyData 1 2 3 -- or -- def = MyData {a = 1, b = 2, c = 3}
makeMyData :: Int -> Int -> MyData makeMyData a' b' = def { a = a', b = b'}
myData1 = (makeMyData 9 10) {a = 1} myData2 = (makeMyData 11 12) {c = 12}
With syntax highlighting: http://haskell.pastebin.com/LxtLZCtL
HTH, Rahul
Thanks to all!
myData3 = (makeMyData my_a my_b) {x=x', z=z'} approach is not working..
I checked again - it works actually! -- Thanks, Sergey
participants (3)
-
Brent Yorgey
-
Rahul Kapoor
-
Sergey Mironov