【发布时间】: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。