函数返回带有修改字段的Haskell记录 [英] Function to return a Haskell record with a modified field

查看:94
本文介绍了函数返回带有修改字段的Haskell记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

我正在编写一个函数,它将一个新的 a 列表并返回一个新的 MyRecord

  pushOntoList :: a  - > MyRecord  - > MyRecord 

问题

有没有办法写 pushOntoList 是这样一种方式,它不依赖于记录其余部分的内容,而只是简单地将它返回而未修改?

另一个问这个问题的方法是,你可以在没有看到的其余部分的情况下编写 pushOntoList MyRecord 定义?

解决方案

是的,非常容易使用记录访问器/标签语法:

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



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

code>

eg

  data MyRecord a = MyRecord {list :: [a],other_fields :: Char} 
派生显示

main = do
let a = MyRecord []'x'
b = a {list ='x':list a}
return(a,b)


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?

解决方案

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)

这篇关于函数返回带有修改字段的Haskell记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆