Function to return a Haskell record with a modified field

不羁的心 提交于 2020-01-11 04:31:20

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/5864388/function-to-return-a-haskell-record-with-a-modified-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!