使用默认值初始化记录的常规做法是什么,除非明确指定这些记录?
为了说明我的问题,请使用此python代码:
class Encoder:
def __init__ (self, minLength = 1, maxLength = 258, maxDistance = 32768):
self.__minLength = minLength
self.__maxLength = maxLength
self.__maxDistance = maxDistance
self.__window = []
self.__buffer = []
现在我正在尝试在erlang中执行相同的操作,即创建具有可覆盖默认值的记录。到目前为止,我的解决方案如下:
-record (encoder, {minLength, maxLength, maxDistance, window = [], buffer = [] } ).
init (Options) ->
case lists:keyfind (minLength, 1, Options) of
false -> MinLength = 3;
{minLength, MinLength} -> pass
end,
case lists:keyfind (maxLength, 1, Options) of
false -> MaxLength = 258;
{maxLength, MaxLength} -> pass
end,
case lists:keyfind (maxDistance, 1, Options) of
false -> MaxDistance = 32768;
{maxDistance, MaxDistance} -> pass
end,
#encoder {minLength = MinLength,
maxLength = MaxLength,
maxDistance = MaxDistance}.
这很笨拙。
我的问题是:
pass
?答案 0 :(得分:5)
您可以使用proplists模块:
-record (encoder, {minLength, maxLength, maxDistance, window = [], buffer = [] } ). init (Options) -> #encoder {minLength = proplists:get_value(minLength, Options, 1), maxLength = proplists:get_value(maxLength, Options, 256), maxDistance = proplists:get_value(maxDistance, Options, 32768)}.