[Erlang] What are the pitfalls for future generations? (1)

Source: Internet
Author: User
Tags setcookie try catch
??

1. if an error occurs in guard, no error is reported. Only false is returned!

case 1=:1 of     true when not erlang:length(t) =:= 1 orelse true ->           ok;     _ ->         errorend.
Result is: Error

An error occurs when length is obtained for T (atom) in the protection formula, which should have been crash. However, in the protection formula, the default error occurs and the protection formula calculation ends and false is returned, this is one of the reasons why the protection class does not accept complex functions and can only use Erlang's BIF.

2. If the catch type is not specified during try catch, the default value is throw!

try_catch(Value) ->    try        case Value  of            error -> erlang:error({error,plz_catch_me});            throw -> erlang:throw({throw,oh_get_you});            exit -> erlang:exit({exit,sorry_by_mistake})        end    catch        T -> T    end.

Result:

So it is best to: clear: Catch throw: T-> {Throw, t}; error: T-> {error, t}; Exit: T-> {exit, t} end.

 

3. Be careful when using Erlang: length/1 in the protection mode! (To traverse the list, the length of time is not fixed)

% The time consumed and the list length are square: Do not do thisfoo (list) When lenght (list)> 0-> do_something; Foo (_)-> done. % use the matching mode to determine the arbitrary length of better ([one])-> do_something_one (); better ([ONE, TWO])-> do_something_two (); better ([ONE, TWO | _])-> do_something_big (); better ([])-> do_something_empty () end.

Tip: To determine whether list is a non-empty list, use case list of [_ | _]-> do_something (); _-> done end.

4. ++ is just an alias for lists: append/2: If you want to use it, be sure to confirm the shortlist ++ longlist! (Can be counted as the length of the negative senseShort length... I think about it every time I use it)

%% DO NOT DOnaive_reverse([H|T]) ->    naive_reverse(T)++[H];naive_reverse([]) ->    [].

Which is the most inefficient way there is to reverse a list. since the ++ operator copies its left operand, the result will be copied again and again... leading to quadratic complexity.

This is the least efficient way to reverse a list, "++" WillCopy left.

But on the other hand: the following usage is fine:

 
%% OKnaive_but_ok_reverse([H|T], Acc) ->    naive_but_ok_reverse(T, [H]++Acc);naive_but_ok_reverse([], Acc) ->    Acc.

This is not a very bad attempt. Each list element is copied only once, and the increasing ACC is on the right side of ++.

Of course, the best practice is as follows:

%% Best Dovanilla_reverse([H|T], Acc) ->    vanilla_reverse(T, [H|Acc]);vanilla_reverse([], Acc) ->    Acc.

This is a little more efficient than above. You don't have to create a list element, just copy it directly (or: if the compiler does not rewrite [H] ++ ACC to [H | ACC], it is more efficient ).

5. There is a big difference between receive and case, although the statement is similar:

case_test(Value) ->    case Value of        1 -> ok;        2 -> error    end.receive_test(Value)when Value>2 ->    PID = spawn(fun () ->        receive            {msg,1} ->                ok;            {msg,2} ->                error        end    end),    [begin PID ! {msg,ValueT} end ||ValueT<-lists:seq(3,Value)],    PID.

Result:

We can see from the above:

5.1 if the case does not match, an error occurs;

5.1 recieve will be blocked when there is no matching message. As long as there is no matching message in the mailbox, it will be suspended during the waiting period. = when there is a new message, it will be awakened, the receive will first check the oldest message (in the queue header) and try to match it as in the case expression. If it cannot be found, the next message will continue. If it matches with the current message successfully, the message is removed from the mailbox and the body of the sub-statement is executed, if no suitable message is found, it will wait until timeout (If yes, after times ).

6. When ERL uses-noshell-noinput to start a node, it cannot be seen and cannot be entered. How can this problem be debugged? Use-remsh Parameters

> Erl-name [email protected]-setcookie 123456-noshell-noinput> Erl-name [email protected]-setcookie 123456-remsh [email protected] % note that the starting node is foo. oh, it's not Bob! [Email protected]> nodes (). [email protected] 127.0.0.1> ['[email protected]'] [email protected] 127.0.0.1> node (). [email protected] 127.0.0.1> '[email protected]'

The pitfalls here are:

6.1 call Q () on a remote node (),Both nodes exit.! It's terrible. It's best to rewrite the Q () function in user_default.erl to prevent him from executing init: Stop ().

6.2 replace ERL with werl in the window;

6.3 ERL supports custom parameters. For example, if you write Erl-rmsh test, no error will be reported. If you accidentally write an error, it will take a long time to query ........

Tip:Two nodes A and B have been started. Use a to control B. You can use Ctrl + G r nodea J 2 in A. For details, see learn some Erlang remote shell.

 

7. If there is an Arglist that is passed in from unknown places like this: "[test1, Test2, test3]", how can we use it for dynamic execution?

Scenario: the method used to call a method: method uses Erlang: Apply (module, method, Arglist) to call the result. The Arglist does not conform to the following format:

% String = "[test1, Test2, 4]." note the end of the last section! String_to_args (string)-> {OK, scan1, _} = erl_scan: string (string), {OK, p} = erl_parse: parse_exprs (scan1), {value, value, []} = erl_eval: exprs (p, []), value.

All the parameters in the above suitable list are bound: if there is a variable such as test1, I have not tried it and have not encountered such a requirement.

Refer

 

8. The ERL startup parameters can be defined by yourself, as shown in figure

>erl -test erlang1  -test hello -test1 test1>init:get_argument(test).{ok,[["erlang1"],["hello"]]>init:get_arguments().[{root,["C:\\Program Files\\erl6.0"]}, {progname,["erl"]}, {home,["C:\\Users\\**"]}, {test,["erlang1"]}, {test,["hello"]}]

8.1 do not define the parameter as a string, for example, "Hello World"

8.2 If This Is used to start the application, do not count on using this custom parameter. Use config to define it.

Applications shocould not normally be configured with command line flags, but shocould use the application environment instead. Refer to keep ing an application in the design principles Chapter for details

 

9. Remember that you are in distributed when using RPC, always pay attention to the process you are in!

For example, if you put RPC: Call in the loop and get different efficiency feedback from the outside, the results in the following example are equivalent, but the first method will issue a lot of calls, the second method has only one call.

 
%%Example - Bad[rpc:call(node, ets, lookup, [table, K]) || K <- ListOfKeys].%%Example - Goodrpc:call(node, ?MODULE, get_data, [ListOfKeys, []]).get_data([], Out) -> lists:reverse(Out);get_data([K|ListOfKeys], Out) -> get_data(ListOfKeys, [ets:lookup(table,K)|Out]).

Similarly, you can change it by yourself: [gen_server: Call (PID, {func, fun}) | Fun <-funlist].

In short, do not send messages once.
10. Do not create a terms (or you cannot control the size of terms ).
Specifically, if you want to traverse all the elements in ETS, the results obtained from ETS: tab2list/1 may be very large. What can we do!
% All elements are also generated at a time: do not do this for bad_traverse_to_print ()-> [begin print (person) end | person <-ETS: tab2list (person)], OK. % from the first to the last one: data needs to be moved from the ERTs to the process. When ETS is very large, good_traverse_to_print ()-> good_traverse_to_print2 (ETS: first (person )). outputs ('$ end_of_table')-> OK; good_traverse_to_print2 (key)-> [person] = ETS: Lookup (person, Key), print (person), good_traverse_to_print2 (ETS: next (person, key) ). % Paging: Best practice ETS: select match matchspec: ETS internally compiles matchspec into opcode and then copies the required data to the process during Eval, greatly reducing the data volume best_traverse_to_print ()-> case ETS: Match (person, '$ 1', 10) of {personlist,' $ end_of_table '}-> [begin print (person) end | [person] <-personlist]; {personlist, key}-> [begin print (person) end | [person] <-personlist], best_traverse_to_print2 (key) End, OK. best_traverse_to_print2 (key)-> case ETS: Match (key) of {personlist, '$ end_of_table'}-> [begin print (person) end | [person] <-personlist]; {personlist, key2}-> [begin print (person) end | [person] <-personlist], best_traverse_to_print2 (key2) end. print (person)-> IO: Format ("name ~ P Phone :~ P ~ N ", [person # person. Name, person # person. Phone]), OK.
There are seemingly contradictions between 10th and 9th. One is that if one processing can be completed, it should not be done multiple times. The other is that if it is too large, it should be processed multiple times! Note: If a message body is too large, it should be repeated.

[Erlang] What are the pitfalls for future generations? (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.