Get the App
SLTechnology News&Howtos  ›  Development  › 

Case Analysis of Erlang functions, clauses and Protective clauses

Shulou Source: shulou.com Published: 2022-06-01 01:06:05 10月03日 Update

This article introduces the relevant knowledge of "Erlang function, clause protective case analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Function:

% This is a simple Erlang module% Test.-module (helloworld).-export ([pie/0, print/1]) .pie ()-> 3.14.print (Msg)-> io:format ("The Message is ~ p", [Msg])% ~ p prints Erlang polynomials in a beautified way, ~ n indicates inserting a newline character, and ~ w indicates printing an Erlang string

Function clause:

-module (helloworld).-export ([area/1, either_or_both/2]).% "_" indicates omitting mode either_or_both (true, _)-> true;either_or_both (_, true)-> false;either_or_both (false, false)-> false Area ({a, X, Y})-> io:format ("a, X, Y: ~ p, ~ p, ~ p], [a, X, Y]); area ({b, X, Y})-> io:format (" b, X, Y: ~ p, ~ p, ~ p ", [b, X, Y]). % compile: C (helloworld).% call function: 1 > helloworld:area ({a, 500,500}) .a, X, Y: a, 500, 500.ok2 >

Note: clauses are separated by divisions and the last clause ends with a full stop. It is agreed that all clauses of a function must have the same function name and the same number of parameters, and must be defined in the same place, and no other function definitions are allowed to be inserted between two clauses of the same function.

For the either_or_both function, if the argument passed is either_or_both (true, 42), it is obviously true, it will only calmly return true, so we need to use our protection.

Clause protection:

-module (helloworld).-export ([either_or_both/2]) .either_or_both (true, B) when is_boolean (B)-> true;either_or_both (A, true) when is_boolean (A)-> false;either_or_both (false, false)-> false

Clause protection starts with the keyword when and ends with the-> symbol. Most operators can be used (+, -, *, /, +, etc.), and some built-in functions can be used, such as self (), is_boolean (...), is_integer (...), is_atom (...). Etc., but you cannot call custom functions or functions in other modules.

This is the end of the Erlang function, clause and clause protective case analysis. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Functions clauses protection examples case analysis analysis same content parameters more knowledge practicality learning and then between the two keys keywords dilemmas most of them. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Technology macOS Shulou Information vpn