[Erl_question16] Why should I use MFA instead of fun ()-> end?

Source: Internet
Author: User

MFA: Module function arguments.

First, you need to know the differences between module: func (ARGs) and func (ARGs?

If you are interested in the details, you can learn about: http://www.cnblogs.com/zhongwencool/p/erlang_hot_code.html

In short: Erlang functions have the difference between local call and external call. Local call is called in the defined module and can be called directly: func (ARGs ); external call is an explicit call that uses module: func (ARGs) to call or import other modules.

When two versions of the same module are loaded, all local calls can work in the current version. However, external call can only be called to the latest version!

1. Fun scenarios:

1.1 first start one shell terminal named test1:

erl -name test1

1.2 test1 loading module mfa_test.erl

-module(mfa_fun).-export([cal/2,func/0]).cal(X,Y) ->     X+Y.func() ->       fun(X,Y) -> cal(X,Y) end.

1.3 input in shell:

>Func = mfa_fun:func().#Fun<mfa_fun.1.52492151>>Func(1,2).3

2. MFA scenarios:

Change the cal function in mfa_test.erl and re-load this module:

cal(X,Y) -> X*Y .

1.5 run again:

>Func(1,2).3

You can see the local version of the func running. If you change func to the following version:

func() ->       fun(X,Y) -> ?MODULE:cal(X,Y) end.

The result is the latest version of code that will be called forever. If you are interested, you can verify it by yourself. Why is the func variable unchanged, but the result has changed...

We can further consider:

We often use spawn (func) to create a new process. If we never upgrade, what will happen if it is a hot upgrade?

You cannot change the local call func, so it is best to use it normally:

Spawn (mod, funcname, argS) to create a process, which does not affect the upgrade.

FurtherAll local calls stored in the process cannot be upgraded. The best practice is to always use MFA!

 

Choice is more important than hard work. Be grateful in time and cherish life.

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.