有没有一种方法可以添加案例,如果发现某些内容,只会将一些数据添加到记录中

Is there a way to add case that will add only some data to Record if it find something

我有一个程序可以检查程序状态的内容是否符合预期状态。在定义稍后将在程序中使用的 Record123 时,我想检查是否 ProgramState returns premium,如果是,则添加 'PremiumValue' = true 进行记录,否则什么都不做。

#'Record123'{
    'SomeRecordData1'
    'SomeRecordData2'
    .
    .
    .
    case lib_proc:(ProgramState) of
        premium ->
            'PremiumValue' = true;
        _ ->
            %%do nothing
    end,
}

我唯一能让它工作的方法是将案例结果分配给 'PremiumValue' 但当 lib_proc/1 returns 除了 premium 之外它不会工作。然后它将无法检查是否收到预期的记录。

#'Record123'{
    'SomeRecordData1'
    'SomeRecordData2'
    .
    .
    .
    'PremiumValue' = case lib_proc:(ProgramState) of
        premium ->
             true
    end,
}

我想知道如果它收到不同的东西,是否可以不做任何事情。

在 Erlang 中,记录中的每个字段总是有一个值。如果不指定值,则默认为 undefined。所以你可以明确指定默认值:

#'Record123'{
    'SomeRecordData1'
    'SomeRecordData2'
    .
    .
    .
    'PremiumValue' = case lib_proc(ProgramState) of
        premium ->
            true;
        _ ->
            undefined
    end,
}

您也可以在后面的步骤中进行:

MyRecord1 = #'Record123'{
    'SomeRecordData1' = apple,
    'SomeRecordData2' = orange
},
MyRecord2 =
    case lib_proc(ProgramState) of
        premium ->
            %% update the PremiumValue field 
            MyRecord1#'Record123'{'PremiumValue' = true};
        _ ->
            %% leave the record unchanged
            MyRecord1
    end,

请注意,由于 Erlang 的单一赋值功能,严格来说,您是用更新的字段创建一个副本并将其存储在变量 MyRecord2 中。原始记录仍可在变量 MyRecord1 中访问,因此请确保您稍后使用正确的变量名称。

您可以在记录定义中设置默认值,在本例中可能为 false。 您也可以这样做以避免一起设置新值:

 Rec = case lib_proc(ProgramState) of 
   premium -> #'Record123'{... 'PremiumValue' = true ...}; 
   _Else -> #'Record123'{...}
 end.