haskell - 通过更改一个值创建新记录

标签 haskell record

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

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
                  }

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

最佳答案

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

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}) = af ( C {a}) = a)

{-# LANGUAGE NamedFieldPuns #-}
baz b@(Sample_Record {record_field1, record_field2, record_field3 = 0}) = 
   b{ record_field3 = record_field1 + record_field2 }

关于haskell - 通过更改一个值创建新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048559/

相关文章:

php - 如何在php中用_替换空格

java - java中两个整数值相等?

plot - 绘制图形时像素与记录的关系

haskell - 如何在 Haskell 中表示时间间隔?

haskell - 计算 Haskell 中的变化

haskell - Haskell 中的单元测试 IO Int 和类似的

android - 如何录制 Android 设备屏幕?

haskell - 使用 Haskell 包拆分时如何组合多个拆分标准?

haskell - 如何在 Haskell 中进行就地快速排序

python - 需要通过用户输入(GPIO.input)结束子进程的循环