使用默认值初始化记录

时间:2011-08-01 00:25:13

标签: erlang default record

使用默认值初始化记录的常规做法是什么,除非明确指定这些记录?

为了说明我的问题,请使用此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}.

这很笨拙。

我的问题是:

  • 是否有一些语言结构或语法糖可以为我节省所有这些代码?
  • 实现这一目标的常见做法是什么?
  • 使用的常用做法是代替我明显从python中偷走的原子pass

1 个答案:

答案 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)}.