5

假设我的记录(具有大量字段)定义如下:

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
                  }

我可以创建一个已修改其中一个字段的类型Sample_Record的新记录吗?a

4

1 回答 1

11

是的。我们有很多方法。简单的是

foo b = b {record_field1 = 1}

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

我们有一些扩展。通配符允许不使用模式中的所有记录,

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

通过NamedFieldPuns扩展,我们可以将记录字段用作值而无需额外的样板(f (C {a=a}) = a与 相同f (C {a}) = a

{-# LANGUAGE NamedFieldPuns #-}
baz b@(Sample_Record {record_field1, record_field2, record_field3 = 0}) = 
   b{ record_field3 = record_field1 + record_field2 }
于 2013-09-27T10:42:02.480 回答