erlangerlang-otperlang-shell

Check if a value is present in a record or not?


Suppose I have a record named #parameters, and I am accessing it from outside and I do not know if all the keys inside it have a value stored with it.

Suppose there is a key in my record named Index. How can I check if the value for Index is present in my record or not? And how do I put it in a case statement like:

Index = find from the record  
or else put it as 100.

Solution

  • I am accessing it from outside and I do not know if all the keys inside it have a value stored with it.

    All fields in a record have a value. If a default value for a field is not specified in the record definition, then erlang uses the atom undefined for the default value. For instance:

    -module(a).
    -compile(export_all).
    
    -record(pattern, {a, b=0, c}).
    
    go() ->
        #pattern{a=1}.
    

    In the shell,

    1> c(a).
    a.erl:2:2: Warning: export_all flag enabled - all functions will be exported
    %    2| -compile(export_all).
    %     |  ^
    {ok,a}
    
    2> rr(a).
    [pattern]
    
    3> a:go().
    #pattern{a = 1,b = 0,c = undefined}
    

    Suppose there is a key in my record named Index; how can I check if the value for Index is present in my record or not?

    Once again, there will always be a value for the index key. Here's an example that demonstrates how to do one thing if index has the value undefined and do something else if index has some other value.

    -module(a).
    -compile(export_all).
    
    -record(pattern, {a, b=0, index}).
    
    go() ->
        Pattern1 = #pattern{a=1},
        check_index(Pattern1),
        Pattern2 = #pattern{a=1, index=10},
        check_index(Pattern2).
    
    check_index(#pattern{index=undefined}) ->
        io:format("index key is undefined~n");
    check_index(#pattern{index=Number}) ->
        io:format("index key is ~w~n", [Number]).
    

    In the shell:

    1> c(a).  
    a.erl:2:2: Warning: export_all flag enabled - all functions will be exported
    %    2| -compile(export_all).
    %     |  ^
    {ok,a}
    
    2> rr(a). 
    [pattern]
    
    3> a:go().
    index key is undefined
    index key is 10
    ok
    

    You could also turn the check_index() function into a boolean function that returns true or false.