Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Erlang Built-in Function (BIF)


May 13, 2021 Erlang


Table of contents


Erlang Built-in Function (BIF)

Built-in functions are those that are built into the Erlang virtual machine for some reason. B uilt-in functions often implement functions that are not easy to implement in Erlang or that are inefficient in Erlang. S ome built-in functions can also be called with only the function name because they belong to the erlang module by default. F or example, the following call to the built-in function trunc is equivalent to calling erlang:trunc.

As shown below, determine whether a leap year is a leap year. L eap year if it can be divided by 400. T o determine, divide the year by 400 and remove the small part with the trunc function. T hen multiply the result by 400 to determine if the initial value is obtained. F or example, in 2004:

2004 / 400 = 5.01
trunc(5.01) = 5
5 * 400 = 2000

Unlike 2004, 2004 cannot be divided by 400. A nd for 2000,

2000 / 400 = 5.0
trunc(5.0) = 5
5 * 400 = 2000

Therefore, 2000 is a leap year. T he next two trunc test examples determine whether a year can be divided by 100 or 4. F irst, the first if statement returns a leap or not_leap value, which is stored in the variable Leap. T his variable is used in the condition test of the later feb to calculate how many days there are in February.

This example demonstrates how trunc is used. I n fact, it's much easier to find the remainder in Erlang using the built-in function rem. H ere's an example:

74> 2004 rem 400.
4

So the following code can also be rewritten:

trunc(Year / 400) * 400 == Year ->
    leap;

Can be rewritten to:

Year rem 400 == 0 ->
    leap;

In addition to trunc, there are many built-in functions in Erlang. O nly a few of them can be used in the guard, and you can't use custom functions (reference guard sequences) in the guard. ( Advanced topic: This does not guarantee that the guard will have no side effects). L et's test some built-in functions in the shell:

75> trunc(5.6).
5
76> round(5.6).
6
77> length([a,b,c,d]).
4
78> float(5).
5.0
79> is_atom(hello).
true
80> is_atom("hello").
false
81> is_tuple({paris, {c, 30}}).
true
82> is_tuple([paris, {c, 30}]).
false

All of these functions can be used in the guard condition test. T he following functions are not available in the guard condition test:

83> atom_to_list(hello).
"hello"
84> list_to_atom("goodbye").
goodbye
85> integer_to_list(22).
"22"

These three built-in functions complete the type conversion. I t is almost impossible to achieve such a transformation in an Erlang system (not in an Erlang virtual machine).