14

Given:

data MyRecord a = MyRecord{list :: [a], other_fields :: Char, …}

I am trying to write a function which puts a new a on list and returns a new MyRecord:

pushOntoList :: a -> MyRecord -> MyRecord

Question:

Is there a way to write pushOntoList is such a way that it does not depend on what is in the rest of the record, but simply gives it back unmodified?

Another way to ask this is can you write pushOntoList without seeing the rest of the MyRecord definition?

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
John F. Miller
  • 26,961
  • 10
  • 71
  • 121
  • 2
    If you are doing anything the slightest bit nontrivial with record fields, I suggest looking into fclabels or data-accessor to give you composable record accessors. Haskell's records are totally ugly and nerfed. – luqui May 03 '11 at 02:48

1 Answers1

20

Yes, very easily using the record accessor/label syntax:

b = a { list = 'x' : list a }

as in the function:

pushOntoList c a = a { list = c : list a }

e.g.

data MyRecord a = MyRecord {list :: [a], other_fields :: Char}
    deriving Show

main = do
    let a = MyRecord [] 'x'
        b = a { list = 'x' : list a }
    return (a,b)
Don Stewart
  • 137,316
  • 36
  • 365
  • 468
  • 6
    Yes, that was easy. I would like to point out in my own defense that the syntax simply does not appear anywhere in [Learn You Some Haskell for Great Good](http://learnyouahaskell.com/making-our-own-types-and-typeclasses), [Real World Haskell](http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html) or [A Gentle Introduction to Haskell](http://www.haskell.org/tutorial/moretypes.html). – John F. Miller May 03 '11 at 02:35
  • Oh, record syntax is indeed a somewhat obscure and slightly hairy part of the language. And don't even get me started on [the syntactic extensions](http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/syntax-extns.html#record-puns). – Don Stewart May 03 '11 at 02:36
  • 4
    The syntax appears in RWH chapter 10. – sdcvvc May 03 '11 at 11:36
  • 4
    It was a little hard to find, so [here's a direct link to the part in chapter 10](http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format.html#Parse.hs:modifyOffset). – 31eee384 Dec 14 '13 at 19:39