Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to return a Haskell record with a modified field

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?

like image 879
John F. Miller Avatar asked May 03 '11 02:05

John F. Miller


1 Answers

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)
like image 149
Don Stewart Avatar answered Oct 22 '22 06:10

Don Stewart