函数字符串=>;erlang中的记录成员

函数字符串=>;erlang中的记录成员,erlang,records,Erlang,Records,我想知道如何定义函数,函数作为参数接受字符串并返回记录的一个成员。 比如说记录 -record(measurement, { temperature, pm2p5, pm10, pressure, humidity, others=[]}). 还有我的功能片段: update_measurement(Measurement, Type_as_String, Value) -> Measurement#measurement{get_type(Type_as_String) =

我想知道如何定义函数,函数作为参数接受字符串并返回记录的一个成员。 比如说记录

-record(measurement, { temperature, pm2p5, pm10, pressure, humidity, others=[]}).
还有我的功能片段:

update_measurement(Measurement, Type_as_String, Value) -> 
    Measurement#measurement{get_type(Type_as_String) = Value}
我想通过将类型作为字符串传递来更新一个值,但我不知道如何定义函数
get\u type(type\u as\u string)
。 我试过用原子,但没用

差不多

update_measurement(Measurement, Type_as_String, Value) ->
    case Type_as_String of
        "temperature" -> Measurement#measurement{temperature = Value};
        "humidity" -> Measurement#measurement{humidity = Value};
...

不正常,因为我想在其他函数中重用此模式。

如果性能不是您最关心的问题:

update_measurement(Measurement, Type_as_String, Value) ->
    update_field(Measurement, Type_as_String, Value).

update_field(#measurement{} = Record, SKey, Value) ->
     update_field(Record, SKey, Value, record_info(fields, measurement));
% add other records here
update_field(_, _, _) -> error(bad_record).

update_field(Record, SKey, Value, Fields) ->
    update_field(Record, list_to_existing_atom(SKey), Value, Fields, 2).

update_field(Record, Key, Value, [Key|_], N) ->
    setelement(N, Record, Value);
update_field(Record, Key, Value, [_|Fields], N) ->
    update_field(Record, Key, Value, Fields, N+1);
update_field(_, _, _, [], _) ->
    error(bad_key).

record\u info/2
不是一个真正的函数,但您必须提供
度量值作为编译时常量。

如果性能不是您最关心的问题:

update_measurement(Measurement, Type_as_String, Value) ->
    update_field(Measurement, Type_as_String, Value).

update_field(#measurement{} = Record, SKey, Value) ->
     update_field(Record, SKey, Value, record_info(fields, measurement));
% add other records here
update_field(_, _, _) -> error(bad_record).

update_field(Record, SKey, Value, Fields) ->
    update_field(Record, list_to_existing_atom(SKey), Value, Fields, 2).

update_field(Record, Key, Value, [Key|_], N) ->
    setelement(N, Record, Value);
update_field(Record, Key, Value, [_|Fields], N) ->
    update_field(Record, Key, Value, Fields, N+1);
update_field(_, _, _, [], _) ->
    error(bad_key).

record\u info/2
不是真正的函数,但您必须提供
度量值作为编译时常量。

您的意思是
二进制到原子
?但事实上我觉得有点奇怪;你不能只写所有匹配器吗?不,我定义了
get\u type(type\u as\u String)->“temperature”->temperature;“湿度”->湿度但是没有工作,对不起,不明白:您的字符串是二进制还是列表?如果是后者(
“温度”
),则改用
列出原子/1
。像
list_to_atom(“temperature”)=>temperature
。你是说
binary_to_atom
?但事实上我觉得有点奇怪;你不能只写所有匹配器吗?不,我定义了
get\u type(type\u as\u String)->“temperature”->temperature;“湿度”->湿度但是没有工作,对不起,不明白:您的字符串是二进制还是列表?如果是后者(
“温度”
),则改用
列出原子/1
。如
列出原子(“温度”)=>温度