开发者

Initializing record with default values

开发者 https://www.devze.com 2023-03-25 11:44 出处:网络
What is common practice to initializ开发者_StackOverflow社区e a record with default values unless those are specified explicitely?

What is common practice to initializ开发者_StackOverflow社区e a record with default values unless those are specified explicitely?

To illustrate my question take this python code:

class Encoder:
    def __init__ (self, minLength = 1, maxLength = 258, maxDistance = 32768):
        self.__minLength = minLength
        self.__maxLength = maxLength
        self.__maxDistance = maxDistance
        self.__window = []
        self.__buffer = []

Now I am trying to do the same thing in erlang, i.e. create a record with overwritable defaults. My solution so far is the following:

-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}.

This is, well, clumsy.

My questions are:

  • Is there some language construct or syntactic sugar that saves me all this code?
  • What is common practice to achieve this?
  • What is common practice to use in stead of my atom pass which I obviously stole from python?


You could use proplists module like so:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消