【问题标题】:Function string => record member in erlang函数字符串 => erlang 中的记录成员
【发布时间】:2017-04-14 05:57:55
【问题描述】:

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

-record(measurement, { temperature, pm2p5, pm10, pressure, humidity, others=[]}).

还有我的功能片段:

update_measurement(Measurement, Type_as_String, Value) -> 
    Measurement#measurement{get_type(Type_as_String) = Value}

我想通过将类型作为字符串传递来更新值,但我不知道定义函数get_type(Type_as_String)。 我尝试过使用原子,但没有成功。

类似

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

不行,因为我想在其他函数中重用这个模式。

【问题讨论】:

  • 你的意思是binary_to_atom?但事实上这对我来说似乎有点奇怪;你不能只写所有的匹配器吗?
  • 不,我定义了get_type(Type_as_String)-> "temperature"->temperature; "humidity"->humidity; ....,但没有用
  • 对不起,不明白:你的字符串是二进制还是列表?如果是后者 ("temperature"),请改用 list_to_atom/1。喜欢list_to_atom("temperature") => temperature

标签: erlang records


【解决方案1】:

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

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_info/2 不是真正的函数,但您必须提供measurement 作为编译时间常数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 2022-11-10
    • 1970-01-01
    • 2016-05-10
    • 2018-08-26
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多