Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new record with change in one value

Tags:

haskell

record

Suppose my record (with large number of fields) is defined like this:

data Sample_Record = Sample_Record { record_field1 :: Int,
                                     record_field2 :: Int,
                                     record_field3 :: Float
                                    }

a = Sample_Record { record_field1 = 4,
                    record_field2 = 5,
                    record_field3 = 5.4
                  }

Can I make a new record of the type Sample_Record from a which has one of it's field modified ?

like image 468
Sibi Avatar asked Sep 27 '13 10:09

Sibi


People also ask

Which button is used in form to add a new record with specific values?

Add a record to a table or form. Open the table in Datasheet View or the form in Form View. On the Home tab, in the Records group, click New, or click New (blank) record, or press Ctrl+Plus Sign (+).

What can be used to change data in a record?

Answer: SQL UPDATE QUERY is used to update or change existing data in a set of records.


1 Answers

Yes. We have a lot of ways. The simple is

foo b = b {record_field1 = 1}

> foo a
 Sample_Record { record_field1 = 1,record_field2 = 5, record_field3 = 5.4 }

We have some extensions. WildCards allow not to use all record in pattern,

{-# LANGUAGE RecordWildCards #-}
bar b@(Sample_Record {record_field1 = 1,..}) = b {record_field1 = 10}
bar b@(Sample_Record {record_field1 = 2,..}) = b {record_field1 = 20}

With NamedFieldPuns extension we could use record fields as values without extra boilerplate (f (C {a=a}) = a is same as f (C {a}) = a)

{-# LANGUAGE NamedFieldPuns #-}
baz b@(Sample_Record {record_field1, record_field2, record_field3 = 0}) = 
   b{ record_field3 = record_field1 + record_field2 }
like image 130
viorior Avatar answered Sep 23 '22 18:09

viorior