Returns an integer or float that is the arithmetical absolute value of Float or Int, for example: > abs(-3.33). 3.33 > abs(-3). 3 Allowed in guard tests. TypesComputes and returns the adler32 checksum for Data. TypesContinues computing the adler32 checksum by combining the previous checksum, OldAdler, with the checksum of Data. The following code: X = erlang:adler32(Data1), Y = erlang:adler32(X,Data2). assigns the same value to Y as this: Y = erlang:adler32([Data1,Data2]). erlang:adler32_combine(FirstAdler, SecondAdler, SecondSize) -> TypesCombines two previously computed adler32 checksums. This computation requires the size of the data object for the second checksum to be known. The following code: Y = erlang:adler32(Data1), Z = erlang:adler32(Y,Data2). assigns the same value to Z as this: X = erlang:adler32(Data1), Y = erlang:adler32(Data2), Z = erlang:adler32_combine(X,Y,iolist_size(Data2)). alias() -> AliasOTP 24.0 alias(Opts) -> AliasOTP 24.0 TypesOpts = [explicit_unalias | reply] Create an alias which can be used when sending messages to the process that created the alias. When the alias has been deactivated, messages sent using the alias will be dropped. An alias can be deactivated using unalias/1. Currently available options for alias/1: explicit_unaliasThe alias can only be deactivated via a call to unalias/1. This is also the default behaviour if no options are passed or if alias/0 is called. replyThe alias will be automatically deactivated when a reply message sent via the alias is received. The alias can also still be deactivated via a call to unalias/1. Example: server() -> receive {request, AliasReqId, Request} -> Result = perform_request(Request), AliasReqId ! {reply, AliasReqId, Result} end, server(). client(ServerPid, Request) -> AliasReqId = alias([reply]), ServerPid ! {request, AliasReqId, Request}, %% Alias will be automatically deactivated if we receive a reply %% since we used the 'reply' option... receive {reply, AliasReqId, Result} -> Result after 5000 -> unalias(AliasReqId), %% Flush message queue in case the reply arrived %% just before the alias was deactivated... receive {reply, AliasReqId, Result} -> Result after 0 -> exit(timeout) end end. Note that both the server and the client in this example must be executing on at least OTP 24 systems in order for this to work. For more information on process aliases see the Process Aliases section of the Erlang Reference Manual. erlang:append_element(Tuple1, Term) -> Tuple2 TypesReturns a new tuple that has one element more than Tuple1, and contains the elements in Tuple1 followed by Term as the last element. Semantically equivalent to list_to_tuple(tuple_to_list(Tuple1) ++ [Term]), but much faster. Example: > erlang:append_element({one, two}, three).
{one,two,three} apply(Fun, Args) -> term()TypesCalls a fun, passing the elements in Args as arguments. If the number of elements in the arguments are known at compile time, the call is better written as Fun(Arg1, Arg2, ... ArgN). Warning Earlier, Fun could also be specified as {Module, Function}, equivalent to apply(Module, Function, Args). This use is deprecated and will stop working in a future release. apply(Module, Function, Args) -> term()TypesReturns the result of applying Function in Module to Args. The applied function must be exported from Module. The arity of the function is the length of Args. Example: > apply(lists, reverse, [[a, b, c]]). [c,b,a] > apply(erlang, atom_to_list, ['Erlang']). "Erlang" If the number of arguments are known at compile time, the call is better written as Module:Function(Arg1, Arg2, ..., ArgN). Failure: error_handler:undefined_function/3 is called if the applied function is not exported. The error handler can be redefined (see process_flag/2). If error_handler is undefined, or if the user has redefined the default error_handler so the replacement module is undefined, an error with reason undef is generated. atom_to_binary(Atom) -> binary()OTP 23.0 Typesatom_to_binary(Atom, Encoding) -> binary()TypesEncoding = latin1 | unicode | utf8 Returns a binary corresponding to the text representation of Atom. If Encoding is latin1, one byte exists for each character in the text representation. If Encoding is utf8 or unicode, the characters are encoded using UTF-8 where characters may require multiple bytes. Note As from Erlang/OTP 20, atoms can contain any Unicode character and atom_to_binary(Atom, latin1) may fail if the text representation for Atom contains a Unicode character > 255. Example: > atom_to_binary('Erlang', latin1).
<<"Erlang">> atom_to_list(Atom) -> string()TypesReturns a list of unicode code points corresponding to the text representation of Atom, for example: > atom_to_list('Erlang').
"Erlang" > atom_to_list('你好').
[20320,22909] See unicode(3) for how to convert the resulting list to different formats. binary_part(Subject, PosLen) -> binary()OTP R14B TypesExtracts the part of the binary described by PosLen. Negative length can be used to extract bytes at the end of a binary, for example: 1> Bin = <<1,2,3,4,5,6,7,8,9,10>>. 2> binary_part(Bin,{byte_size(Bin), -5}). <<6,7,8,9,10>> Failure: badarg if PosLen in any way references outside the binary. Start is zero-based, that is: 1> Bin = <<1,2,3>> 2> binary_part(Bin,{0,2}). <<1,2>> For details about the PosLen semantics, see binary(3). Allowed in guard tests. binary_part(Subject, Start, Length) -> binary()OTP R14B TypesThe same as binary_part(Subject, {Start, Length}). Allowed in guard tests. binary_to_atom(Binary) -> atom()OTP 23.0 Typesbinary_to_atom(Binary, Encoding) -> atom()TypesEncoding = latin1 | unicode | utf8 Returns the atom whose text representation is Binary. If Encoding is utf8 or unicode, the binary must contain valid UTF-8 sequences. Note As from Erlang/OTP 20, binary_to_atom(Binary, utf8) is capable of decoding any Unicode character. Earlier versions would fail if the binary contained Unicode characters > 255. Note There is configurable limit on how many atoms that can exist and atoms are not garbage collected. Therefore, it is recommended to consider whether binary_to_existing_atom/2 is a better option than binary_to_atom/2. The default limits can be found in efficiency guide (section Advanced). Examples: > binary_to_atom(<<"Erlang">>, latin1).
'Erlang' > binary_to_atom(<<1024/utf8>>, utf8).
'Ѐ' binary_to_existing_atom(Binary) -> atom()OTP 23.0 Typesbinary_to_existing_atom(Binary, Encoding) -> atom()TypesEncoding = latin1 | unicode | utf8 As binary_to_atom/2, but the atom must exist. The Erlang system has a configurable limit for the total number of atoms that can exist, and atoms are not garbage collected. Therefore, it is not safe to create many atoms from binaries that come from an untrusted source (for example, a file fetched from the Internet), for example, using binary_to_atom/2. This function is thus the appropriate option when the input binary comes from an untrusted source. An atom exists in an Erlang system when included in a loaded Erlang module or when created programmatically (for example, by binary_to_atom/2). See the next note for an example of when an atom exists in the source code for an Erlang module but not in the compiled version of the same module. Failure: badarg if the atom does not exist. Note Note that the compiler may optimize away atoms. For example, the compiler will rewrite atom_to_list(some_atom) to "some_atom". If that expression is the only mention of the atom some_atom in the containing module, the atom will not be created when the module is loaded, and a subsequent call to binary_to_existing_atom(<<"some_atom">>, utf8) will fail. binary_to_float(Binary) -> float()OTP R16B TypesReturns the float whose text representation is Binary, for example: > binary_to_float(<<"2.2017764e+0">>).
2.2017764 The float string format is the same as the format for Erlang float literals except for that underscores are not permitted. Failure: badarg if Binary contains a bad representation of a float. binary_to_integer(Binary) -> integer()OTP R16B TypesReturns an integer whose text representation is Binary, for example: > binary_to_integer(<<"123">>).
123 binary_to_integer/1 accepts the same string formats as list_to_integer/1. Failure: badarg if Binary contains a bad representation of an integer. binary_to_integer(Binary, Base) -> integer()OTP R16B Returns an integer whose text representation in base Base is Binary, for example: > binary_to_integer(<<"3FF">>, 16).
1023 binary_to_integer/2 accepts the same string formats as list_to_integer/2. Failure: badarg if Binary contains a bad representation of an integer. binary_to_list(Binary) -> [byte()]TypesReturns a list of integers corresponding to the bytes of Binary. binary_to_list(Binary, Start, Stop) -> [byte()]Types1..byte_size(Binary) As binary_to_list/1, but returns a list of integers corresponding to the bytes from position Start to position Stop in Binary. The positions in the binary are numbered starting from 1. Note The one-based indexing for binaries used by this function is deprecated. New code is to use binary:bin_to_list/3 in STDLIB instead. All functions in module binary consistently use zero-based indexing. binary_to_term(Binary) -> term()TypesReturns an Erlang term that is the result of decoding binary object Binary, which must be encoded according to the Erlang external term format. > Bin = term_to_binary(hello). <<131,100,0,5,104,101,108,108,111>> > hello = binary_to_term(Bin). hello Warning When decoding binaries from untrusted sources, the untrusted source may submit data in a way to create resources, such as atoms and remote references, that cannot be garbage collected and lead to Denial of Service attack. In such cases, consider using binary_to_term/2 with the safe option. See also term_to_binary/1 and binary_to_term/2. binary_to_term(Binary, Opts) -> term() | {term(), Used}OTP R13B04 TypesOpt = safe | used Opts = [Opt] As binary_to_term/1, but takes these options: safeUse this option when receiving binaries from an untrusted source. When enabled, it prevents decoding data that can be used to attack the Erlang runtime. In the event of receiving unsafe data, decoding fails with a badarg error. This prevents creation of new atoms directly, creation of new atoms indirectly (as they are embedded in certain structures, such as process identifiers, refs, and funs), and creation of new external function references. None of those resources are garbage collected, so unchecked creation of them can exhaust available memory. > binary_to_term(<<131,100,0,5,"hello">>, [safe]). ** exception error: bad argument > hello. hello > binary_to_term(<<131,100,0,5,"hello">>, [safe]). hello Warning The safe option ensures the data is safely processed by the Erlang runtime but it does not guarantee the data is safe to your application. You must always validate data from untrusted sources. If the binary is stored or transits through untrusted sources, you should also consider cryptographically signing it. usedChanges the return value to {Term, Used} where Used is the number of bytes actually read from Binary. > Input = <<131,100,0,5,"hello","world">>. <<131,100,0,5,104,101,108,108,111,119,111,114,108,100>> > {Term, Used} = binary_to_term(Input, [used]). {hello, 9} > split_binary(Input, Used). {<<131,100,0,5,104,101,108,108,111>>, <<"world">>} Failure: badarg if safe is specified and unsafe data is decoded. See also term_to_binary/1, binary_to_term/1, and list_to_existing_atom/1. bit_size(Bitstring) -> integer() >= 0TypesReturns an integer that is the size in bits of Bitstring, for example: > bit_size(<<433:16,3:3>>). 19 > bit_size(<<1,2,3>>). 24 Allowed in guard tests. bitstring_to_list(Bitstring) -> [byte() | bitstring()]TypesReturns a list of integers corresponding to the bytes of Bitstring. If the number of bits in the binary is not divisible by 8, the last element of the list is a bitstring containing the remaining 1-7 bits. Examples: > bitstring_to_list(<<433:16>>).
[1,177] > bitstring_to_list(<<433:16,3:3>>).
[1,177,<<3:3>>] erlang:bump_reductions(Reductions) -> true TypesThis implementation-dependent function increments the reduction counter for the calling process. In the Beam emulator, the reduction counter is normally incremented by one for each function and BIF call. A context switch is forced when the counter reaches the maximum number of reductions for a process (4000 reductions in Erlang/OTP 19.2 and later). Warning This BIF can be removed in a future version of the Beam machine without prior warning. It is unlikely to be implemented in other Erlang implementations. byte_size(Bitstring) -> integer() >= 0TypesReturns an integer that is the number of bytes needed to contain Bitstring. That is, if the number of bits in Bitstring is not divisible by 8, the resulting number of bytes is rounded up. Examples: > byte_size(<<433:16,3:3>>). 3 > byte_size(<<1,2,3>>). 3 Allowed in guard tests. erlang:cancel_timer(TimerRef) -> Result TypesResult = Time | false erlang:cancel_timer(TimerRef, Options) -> Result | ok OTP 18.0 TypesOption = {async, Async} | {info, Info} Options = [Option] Result = Time | false Cancels a timer that has been created by erlang:start_timer or erlang:send_after. TimerRef identifies the timer, and was returned by the BIF that created the timer. Options: {async, Async}Asynchronous request for cancellation. Async defaults to false, which causes the cancellation to be performed synchronously. When Async is set to true, the cancel operation is performed asynchronously. That is, cancel_timer() sends an asynchronous request for cancellation to the timer service that manages the timer, and then returns ok. {info, Info}Requests information about the Result of the cancellation. Info defaults to true, which means the Result is given. When Info is set to false, no information about the result of the cancellation is given.
More Options may be added in the future. If Result is an integer, it represents the time in milliseconds left until the canceled timer would have expired. If Result is false, a timer corresponding to TimerRef could not be found. This can be either because the timer had expired, already had been canceled, or because TimerRef never corresponded to a timer. Even if the timer had expired, it does not tell you if the time-out message has arrived at its destination yet. Note The timer service that manages the timer can be co-located with another scheduler than the scheduler that the calling process is executing on. If so, communication with the timer service takes much longer time than if it is located locally. If the calling process is in critical path, and can do other things while waiting for the result of this operation, or is not interested in the result of the operation, you want to use option {async, true}. If using option {async, false}, the calling process blocks until the operation has been performed. See also erlang:send_after/4, erlang:start_timer/4, and erlang:read_timer/2. ceil(Number) -> integer()OTP 20.0 TypesReturns the smallest integer not less than Number. For example: Allowed in guard tests. check_old_code(Module) -> boolean()OTP R14B04 Typescheck_process_code(Pid, Module) -> CheckResultTypescheck_process_code(Pid, Module, OptionList) -> CheckResult | asyncOTP 17.0 TypesOption = {async, RequestId} | {allow_gc, boolean()} OptionList = [Option] Checks if the node local process identified by Pid executes old code for Module. Options: {allow_gc, boolean()}Determines if garbage collection is allowed when performing the operation. If {allow_gc, false} is passed, and a garbage collection is needed to determine the result of the operation, the operation is aborted (see information on CheckResult below). The default is to allow garbage collection, that is, {allow_gc, true}. {async, RequestId}The function check_process_code/3 returns the value async immediately after the request has been sent. When the request has been processed, the process that called this function is passed a message on the form {check_process_code, RequestId, CheckResult}. If Pid equals self(), and no async option has been passed, the operation is performed at once. Otherwise a request for the operation is sent to the process identified by Pid, and is handled when appropriate. If no async option has been passed, the caller blocks until CheckResult is available and can be returned. CheckResult informs about the result of the request as follows: trueThe process identified by Pid executes old code for Module. That is, the current call of the process executes old code for this module, or the process has references to old code for this module, or the process contains funs that references old code for this module. falseThe process identified by Pid does not execute old code for Module. abortedThe operation was aborted, as the process needed to be garbage collected to determine the operation result, and the operation was requested by passing option {allow_gc, false}. Note Up until ERTS version 8.*, the check process code operation checks for all types of references to the old code. That is, direct references (e.g. return addresses on the process stack), indirect references (funs in process context), and references to literals in the code. As of ERTS version 9.0, the check process code operation only checks for direct references to the code. Indirect references via funs will be ignored. If such funs exist and are used after a purge of the old code, an exception will be raised upon usage (same as the case when the fun is received by the process after the purge). Literals will be taken care of (copied) at a later stage. This behavior can as of ERTS version 8.1 be enabled when building OTP, and will automatically be enabled if dirty scheduler support is enabled. See also code(3). Failures: badargIf Pid is not a node local process identifier. badargIf Module is not an atom. badargIf OptionList is an invalid list of options.erlang:convert_time_unit(Time, FromUnit, ToUnit) -> ConvertedTime OTP 18.0 TypesConverts the Time value of time unit FromUnit to the corresponding ConvertedTime value of time unit ToUnit. The result is rounded using the floor function. Warning You can lose accuracy and precision when converting between time units. To minimize such loss, collect all data at native time unit and do the conversion on the end result. TypesComputes and returns the crc32 (IEEE 802.3 style) checksum for Data. TypesContinues computing the crc32 checksum by combining the previous checksum, OldCrc, with the checksum of Data. The following code: X = erlang:crc32(Data1), Y = erlang:crc32(X,Data2). assigns the same value to Y as this: Y = erlang:crc32([Data1,Data2]). erlang:crc32_combine(FirstCrc, SecondCrc, SecondSize) -> TypesCombines two previously computed crc32 checksums. This computation requires the size of the data object for the second checksum to be known. The following code: Y = erlang:crc32(Data1), Z = erlang:crc32(Y,Data2). assigns the same value to Z as this: X = erlang:crc32(Data1), Y = erlang:crc32(Data2), Z = erlang:crc32_combine(X,Y,iolist_size(Data2)). date() -> DateTypesReturns the current date as {Year, Month, Day}. The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time. Example: erlang:decode_packet(Type, Bin, Options) -> TypesType = Options = [Opt] HttpPacket = HttpRequest = {http_request, HttpMethod, HttpUri, HttpVersion} HttpResponse = HttpHeader = HttpError = {http_error, HttpString} HttpMethod = HttpUri = HttpField = Decodes the binary Bin according to the packet protocol specified by Type. Similar to the packet handling done by sockets with option {packet,Type}. If an entire packet is contained in Bin, it is returned together with the remainder of the binary as {ok,Packet,Rest}. If Bin does not contain the entire packet, {more,Length} is returned. Length is either the expected total size of the packet, or undefined if the expected packet size is unknown. decode_packet can then be called again with more data added. If the packet does not conform to the protocol format, {error,Reason} is returned. Types: raw | 0No packet handling is done. The entire binary is returned unless it is empty. 1 | 2 | 4Packets consist of a header specifying the number of bytes in the packet, followed by that number of bytes. The length of the header can be one, two, or four bytes; the order of the bytes is big-endian. The header is stripped off when the packet is returned. lineA packet is a line-terminated by a delimiter byte, default is the latin-1 newline character. The delimiter byte is included in the returned packet unless the line was truncated according to option line_length. asn1 | cdr | sunrm | fcgi | tpktThe header is not stripped off. The meanings of the packet types are as follows: asn1 - ASN.1 BERsunrm - Sun's RPC encodingcdr - CORBA (GIOP 1.1)fcgi - Fast CGItpkt - TPKT format [RFC1006] http | httph | http_bin | httph_binThe Hypertext Transfer Protocol. The packets are returned with the format according to HttpPacket described earlier. A packet is either a request, a response, a header, or an end of header mark. Invalid lines are returned as HttpError. Recognized request methods and header fields are returned as atoms. Others are returned as strings. Strings of unrecognized header fields are formatted with only capital letters first and after hyphen characters, for example, "Sec-Websocket-Key". Header field names are also returned in UnmodifiedField as strings, without any conversion or formatting. The protocol type http is only to be used for the first line when an HttpRequest or an HttpResponse is expected. The following calls are to use httph to get HttpHeaders until http_eoh is returned, which marks the end of the headers and the beginning of any following message body. The variants http_bin and httph_bin return strings (HttpString) as binaries instead of lists. Options: {packet_size, integer() >= 0}Sets the maximum allowed size of the packet body. If the packet header indicates that the length of the packet is longer than the maximum allowed length, the packet is considered invalid. Defaults to 0, which means no size limit. {line_length, integer() >= 0}For packet type line, lines longer than the indicated length are truncated. Option line_length also applies to http* packet types as an alias for option packet_size if packet_size itself is not set. This use is only intended for backward compatibility. {line_delimiter, 0 =< byte() =< 255}For packet type line, sets the delimiting byte. Default is the latin-1 character $\n. Examples: > erlang:decode_packet(1,<<3,"abcd">>,[]). {ok,<<"abc">>,<<"d">>} > erlang:decode_packet(1,<<5,"abcd">>,[]). {more,6} erlang:delete_element(Index, Tuple1) -> Tuple2 OTP R16B Types1..tuple_size(Tuple1) Returns a new tuple with element at Index removed from tuple Tuple1, for example: > erlang:delete_element(2, {one, two, three}).
{one,three} delete_module(Module) -> true | undefinedTypesMakes the current code for Module become old code and deletes all references for this module from the export table. Returns undefined if the module does not exist, otherwise true. Warning This BIF is intended for the code server (see code(3)) and is not to be used elsewhere. Failure: badarg if there already is an old version of Module. demonitor(MonitorRef) -> trueTypesIf MonitorRef is a reference that the calling process obtained by calling monitor/2, this monitoring is turned off. If the monitoring is already turned off, nothing happens. Once demonitor(MonitorRef) has returned, it is guaranteed that no {'DOWN', MonitorRef, _, _, _} message, because of the monitor, will be placed in the caller message queue in the future. However, a {'DOWN', MonitorRef, _, _, _} message can have been placed in the caller message queue before the call. It is therefore usually advisable to remove such a 'DOWN' message from the message queue after monitoring has been stopped. demonitor(MonitorRef, [flush]) can be used instead of demonitor(MonitorRef) if this cleanup is wanted. Note Before Erlang/OTP R11B (ERTS 5.5) demonitor/1 behaved completely asynchronously, that is, the monitor was active until the "demonitor signal" reached the monitored entity. This had one undesirable effect. You could never know when you were guaranteed not to receive a DOWN message because of the monitor. The current behavior can be viewed as two combined operations: asynchronously send a "demonitor signal" to the monitored entity and ignore any future results of the monitor. Failure: It is an error if MonitorRef refers to a monitoring started by another process. Not all such cases are cheap to check. If checking is cheap, the call fails with badarg, for example if MonitorRef is a remote reference. demonitor(MonitorRef, OptionList) -> boolean()TypesOptionList = [Option] Option = flush | info The returned value is true unless info is part of OptionList. demonitor(MonitorRef, []) is equivalent to demonitor(MonitorRef). Options: flushRemoves (one) {_, MonitorRef, _, _, _} message, if there is one, from the caller message queue after monitoring has been stopped. Calling demonitor(MonitorRef, [flush]) is equivalent to the following, but more efficient: demonitor(MonitorRef), receive {_, MonitorRef, _, _, _} -> true after 0 -> true endinfo The returned value is one of the following: trueThe monitor was found and removed. In this case, no 'DOWN' message corresponding to this monitor has been delivered and will not be delivered. falseThe monitor was not found and could not be removed. This probably because someone already has placed a 'DOWN' message corresponding to this monitor in the caller message queue. If option info is combined with option flush, false is returned if a flush was needed, otherwise true. Note More options can be added in a future release. Failures: badargIf OptionList is not a list. badargIf Option is an invalid option. badargThe same failure as for demonitor/1.disconnect_node(Node) -> boolean() | ignoredTypesForces the disconnection of a node. This appears to the node Node as if the local node has crashed. This BIF is mainly used in the Erlang network authentication protocols. Returns true if disconnection succeeds, otherwise false. If the local node is not alive, ignored is returned. erlang:display(Term) -> true TypesPrints a text representation of Term on the standard output. Warning This BIF is intended for debugging only. The printed representation may contain internal details that do not match the high-level representation of the term in Erlang. erlang:dist_ctrl_get_data(DHandle) -> {Size, Data} | Data | none OTP 21.0 TypesGet distribution channel data from the local node that is to be passed to the remote node. The distribution channel is identified by DHandle. If no data is available, the atom none is returned. One can request to be informed by a message when more data is available by calling erlang:dist_ctrl_get_data_notification(DHandle). The returned value when there are data available depends on the value of the get_size option configured on the distribution channel identified by DHandle. For more information see the documentation of the get_size option for the erlang:dist_ctrl_set_opt/3 function. Note Only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function. This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. erlang:dist_ctrl_get_opt(DHandle, Opt :: get_size) -> Value OTP 22.0 Typeserlang:dist_ctrl_get_data_notification(DHandle) -> ok OTP 21.0 TypesRequest notification when more data is available to fetch using erlang:dist_ctrl_get_data(DHandle) for the distribution channel identified by DHandle. When more data is present, the caller will be sent the message dist_data. Once a dist_data messages has been sent, no more dist_data messages will be sent until the dist_ctrl_get_data_notification/1 function has been called again. Note Only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function. This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. erlang:dist_ctrl_input_handler(DHandle, InputHandler) -> ok OTP 21.0 Typeserlang:dist_ctrl_put_data(DHandle, Data) -> ok OTP 21.0 Typeserlang:dist_ctrl_set_opt(DHandle, Opt :: get_size, Value) -> OTP 22.0 TypesSets the value of the get_size option on the distribution channel identified by DHandle. This option controls the return value of calls to erlang:dist_ctrl_get_data(DHandle) where DHandle equals DHandle used when setting this option. When the get_size option is: false and there are distribution data available, a call to erlang:dist_ctrl_get_data(DHandle) will just return Data to pass over the channel. This is the default value of the get_size option. true and there are distribution data available, a call to erlang:dist_ctrl_get_data(DHandle) will return Data to pass over the channel as well as the Size of Data in bytes. This is returned as a tuple on the form {Size, Data}.All options are set to default when a channel is closed. Note Only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function. This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. element(N, Tuple) -> term()Types1..tuple_size(Tuple) Returns the Nth element (numbering from 1) of Tuple, for example: > element(2, {a, b, c}).
b Allowed in guard tests. erase() -> [{Key, Val}]TypesReturns the process dictionary and deletes it, for example: > put(key1, {1, 2, 3}), put(key2, [a, b, c]), erase(). [{key1,{1,2,3}},{key2,[a,b,c]}] erase(Key) -> Val | undefinedTypesReturns the value Val associated with Key and deletes it from the process dictionary. Returns undefined if no value is associated with Key. The average time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary. Example: > put(key1, {merry, lambs, are, playing}), X = erase(key1), {X, erase(key1)}. {{merry,lambs,are,playing},undefined} error(Reason) -> no_return()TypesRaises an exception of class error with the reason Reason. As evaluating this function causes an exception to be thrown, it has no return value. The intent of the exception class error is to signal that an unexpected error has happened (for example, a function is called with a parameter that has an incorrect type). See the guide about errors and error handling for additional information. Example: > catch error(foobar).
{'EXIT',{foobar,[{shell,apply_fun,3,
[{file,"shell.erl"},{line,906}]},
{erl_eval,do_apply,6,[{file,"erl_eval.erl"},{line,677}]},
{erl_eval,expr,5,[{file,"erl_eval.erl"},{line,430}]},
{shell,exprs,7,[{file,"shell.erl"},{line,687}]},
{shell,eval_exprs,7,[{file,"shell.erl"},{line,642}]},
{shell,eval_loop,3,[{file,"shell.erl"},{line,627}]}]}}
error(Reason, Args) -> no_return()TypesRaises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function or the atom none. If it is a list, it is used to provide the arguments for the current function in the stack back-trace. If it is none, the arity of the calling function is used in the stacktrace. As evaluating this function causes an exception to be raised, it has no return value. The intent of the exception class error is to signal that an unexpected error has happened (for example, a function is called with a parameter that has an incorrect type). See the guide about errors and error handling for additional information. Example: test.erl: -module(test). -export([example_fun/2]). example_fun(A1, A2) -> erlang:error(my_error, [A1, A2]). Erlang shell: 6> c(test). {ok,test} 7> test:example_fun(arg1,"this is the second argument"). ** exception error: my_error in function test:example_fun/2 called as test:example_fun(arg1,"this is the second argument") error(Reason, Args, Options) -> no_return()OTP 24.0 TypesOptions = [Option] Option = {error_info, ErrorInfoMap} Raises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function or the atom none. If it is a list, it is used to provide the arguments for the current function in the stack back-trace. If it is none, the arity of the calling function is used in the stacktrace. As evaluating this function causes an exception to be raised, it has no return value. If the error_info option is given, the ErrorInfoMap will be inserted into the stacktrace. The information given in the ErrorInfoMap is to be used by error formatters such as erl_error to provide more context around an error. The default module of the ErrorInfoMap is the module that the call to error/3 is made. The default function is format_error. See format_error/2 for more details on how this Module:Function/2 is to be used The intent of the exception class error is to signal that an unexpected error has happened (for example, a function is called with a parameter that has an incorrect type). See the guide about errors and error handling for additional information. exit(Reason) -> no_return()TypesRaises an exception of class exit with exit reason Reason. As evaluating this function causes an exception to be raised, it has no return value. The intent of the exception class exit is that the current process should be stopped (for example when a message telling a process to stop is received). This function differ from error/1,2,3 by causing an exception of a different class and by having a reason that does not include the list of functions from the call stack. See the guide about errors and error handling for additional information. Example: > exit(foobar). ** exception exit: foobar > catch exit(foobar). {'EXIT',foobar} Note If a process calls exit(kill) and does not catch the exception, it will terminate with exit reason kill and also emit exit signals with exit reason kill (not killed) to all linked processes. Such exit signals with exit reason kill can be trapped by the linked processes. Note that this means that signals with exit reason kill behave differently depending on how they are sent because the signal will be untrappable if a process sends such a signal to another process with erlang:exit/2. exit(Pid, Reason) -> trueTypesSends an exit signal with exit reason Reason to the process or port identified by Pid. The following behavior applies if Reason is any term, except normal or kill, and P is the process or port identified by Pid:
The following behavior applies if Reason is the term normal and Pid is the identifier of a process P which is not the same as the process that invoked erlang:exit(Pid, normal) (the behavior when a process sends a signal with the normal reason to itself is described in the warning):
If Reason is the atom kill, that is, if exit(Pid, kill) is called, an untrappable exit signal is sent to the process that is identified by Pid, which unconditionally exits with exit reason killed. The exit reason is changed from kill to killed to hint to linked processes that the killed process got killed by a call to exit(Pid, kill). Note The functions erlang:exit/1 and erlang:exit/2 are named similarly but provide very different functionalities. The erlang:exit/1 function should be used when the intent is to stop the current process while erlang:exit/2 should be used when the intent is to send an exit signal to another process. Note also that erlang:exit/1 raises an exception that can be caught while erlang:exit/2 does not cause any exception to be raised. Warning The only scenario that has not been covered by the description above is when a process P sends an exit signal with reason normal to itself, that is erlang:exit(self(), normal). The behavior in this scenario is as follows:
Note that the behavior described above is different from when a process sends an exit signal with reason normal to another process. This is arguably strange but this behavior is kept for backward compatibility reasons. OTP R14B04 TypesCalculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format. The following condition applies always: > Size1 = byte_size(term_to_binary(Term)), > Size2 = erlang:external_size(Term), > true = Size1 =< Size2. true This is equivalent to a call to: erlang:external_size(Term, []) OTP R14B04 TypesCalculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format. The following condition applies always: > Size1 = byte_size(term_to_binary(Term, Options)), > Size2 = erlang:external_size(Term, Options), > true = Size1 =< Size2. true Option {minor_version, Version} specifies how floats are encoded. For a detailed description, see term_to_binary/2. float(Number) -> float()TypesReturns a float by converting Number to a float, for example: Allowed in guard tests. Note If used on the top level in a guard, it tests whether the argument is a floating point number; for clarity, use is_float/1 instead. When float/1 is used in an expression in a guard, such as 'float(A) == 4.0', it converts a number as described earlier. float_to_binary(Float) -> binary()OTP R16B TypesThe same as float_to_binary(Float,[{scientific,20}]). float_to_binary(Float, Options) -> binary()OTP R16B TypesOptions = [Option] Option = Returns a binary corresponding to the text representation of Float using fixed decimal point formatting. Options behaves in the same way as float_to_list/2. Examples: > float_to_binary(7.12, [{decimals, 4}]). <<"7.1200">> > float_to_binary(7.12, [{decimals, 4}, compact]). <<"7.12">> > float_to_binary(7.12, [{scientific, 3}]). <<"7.120e+00">> > float_to_binary(7.12, [short]). <<"7.12">> > float_to_binary(0.1+0.2, [short]). <<"0.30000000000000004">> > float_to_binary(0.1+0.2) <<"3.00000000000000044409e-01">> float_to_list(Float) -> string()TypesThe same as float_to_list(Float,[{scientific,20}]). float_to_list(Float, Options) -> string()OTP R16B TypesOptions = [Option] Option = Returns a string corresponding to the text representation of Float using fixed decimal point formatting. Available options:
Examples: > float_to_list(7.12, [{decimals, 4}]). "7.1200" > float_to_list(7.12, [{decimals, 4}, compact]). "7.12" > float_to_list(7.12, [{scientific, 3}]). "7.120e+00" > float_to_list(7.12, [short]). "7.12" > float_to_list(0.1+0.2, [short]). "0.30000000000000004" > float_to_list(0.1+0.2) "3.00000000000000044409e-01" In the last example, float_to_list(0.1+0.2) evaluates to "3.00000000000000044409e-01". The reason for this is explained in Representation of Floating Point Numbers. floor(Number) -> integer()OTP 20.0 TypesReturns the largest integer not greater than Number. For example: Allowed in guard tests. erlang:fun_info(Fun) -> [{Item, Info}] TypesItem = Returns a list with information about the fun Fun. Each list element is a tuple. The order of the tuples is undefined, and more tuples can be added in a future release. Warning This BIF is mainly intended for debugging, but it can sometimes be useful in library functions that need to verify, for example, the arity of a fun. Two types of funs have slightly different semantics:
The following elements are always present in the list for both local and external funs: {type, Type}Type is local or external. {module, Module}Module (an atom) is the module name. If Fun is a local fun, Module is the module in which the fun is defined. If Fun is an external fun, Module is the module that the fun refers to. {name, Name}Name (an atom) is a function name. If Fun is a local fun, Name is the name of the local function that implements the fun. (This name was generated by the compiler, and is only of informational use. As it is a local function, it cannot be called directly.) If no code is currently loaded for the fun, [] is returned instead of an atom. If Fun is an external fun, Name is the name of the exported function that the fun refers to. {arity, Arity}Arity is the number of arguments that the fun is to be called with. {env, Env}Env (a list) is the environment or free variables for the fun. For external funs, the returned list is always empty. The following elements are only present in the list if Fun is local: {pid, Pid}Pid is the process identifier of the process that originally created the fun. It might point to the init process if the Fun was statically allocated when module was loaded (this optimisation is performed for local functions that do not capture the environment). {index, Index}Index (an integer) is an index into the module fun table. {new_index, Index}Index (an integer) is an index into the module fun table. {new_uniq, Uniq}Uniq (a binary) is a unique value for this fun. It is calculated from the compiled code for the entire module. {uniq, Uniq}Uniq (an integer) is a unique value for this fun. As from Erlang/OTP R15, this integer is calculated from the compiled code for the entire module. Before Erlang/OTP R15, this integer was based on only the body of the fun. erlang:fun_info(Fun, Item) -> {Item, Info} TypesItem = fun_info_item() fun_info_item() = Returns information about Fun as specified by Item, in the form {Item,Info}. For any fun, Item can be any of the atoms module, name, arity, env, or type. For a local fun, Item can also be any of the atoms index, new_index, new_uniq, uniq, and pid. For an external fun, the value of any of these items is always the atom undefined. See erlang:fun_info/1. erlang:fun_to_list(Fun) -> String :: string() TypesReturns String that represents the code that created Fun. String has the following form, if Fun was created by a fun expression of the form fun ModuleName:FuncName/Arity: "fun ModuleName:FuncName/Arity" The form of String when Fun is created from other types of fun expressions differs depending on if the fun expression was executed while executing compiled code or if the fun expression was executed while executing uncompiled code (uncompiled escripts, the Erlang shell, and other code executed by the erl_eval module): compiled code"#Fun<M.I.U>", where M, I and U correspond to the values named module, index and uniq in the result of erlang:fun_info(Fun). uncompiled codeAll funs created from fun expressions in uncompiled code with the same arity are mapped to the same list by fun_to_list/1.Note Generally, one can not use fun_to_list/1 to check if two funs are equal as fun_to_list/1 does not take the fun's environment into account. See erlang:fun_info/1 for how to get the environment of a fun. Note The output of fun_to_list/1 can differ between Erlang implementations and may change in future versions. Examples: -module(test). -export([add/1, add2/0, fun_tuple/0]). add(A) -> fun(B) -> A + B end. add2() -> fun add/1. fun_tuple() -> {fun() -> 1 end, fun() -> 1 end}. > {fun test:add/1, test:add2()}.
{fun test:add/1,#Fun<test.1.107738983>}
Explanation: fun test:add/1 is upgradable but test:add2() is not upgradable. > {test:add(1), test:add(42)}.
{#Fun<test.0.107738983>,#Fun<test.0.107738983>}
Explanation: test:add(1) and test:add(42) has the same string representation as the environment is not taken into account. >test:fun_tuple().
{#Fun<test.2.107738983>,#Fun<test.3.107738983>}
Explanation: The string representations differ because the funs come from different fun expressions. > {fun() -> 1 end, fun() -> 1 end}. >
{#Fun<erl_eval.45.97283095>,#Fun<erl_eval.45.97283095>}
Explanation: All funs created from fun expressions of this form in uncompiled code with the same arity are mapped to the same list by fun_to_list/1. erlang:function_exported(Module, Function, Arity) -> boolean() TypesReturns true if the module Module is current and contains an exported function Function/Arity, or if there is a BIF (a built-in function implemented in C) with the specified name, otherwise returns false. garbage_collect() -> trueForces an immediate garbage collection of the executing process. The function is not to be used unless it has been noticed (or there are good reasons to suspect) that the spontaneous garbage collection will occur too late or not at all. Warning Improper use can seriously degrade system performance. garbage_collect(Pid) -> GCResultTypesgarbage_collect(Pid, OptionList) -> GCResult | asyncOTP 17.0 TypesOption = {async, RequestId} | {type, major | minor} OptionList = [Option] Garbage collects the node local process identified by Pid. Option: {async, RequestId} The function garbage_collect/2 returns the value async immediately after the request has been sent. When the request has been processed, the process that called this function is passed a message on the form {garbage_collect, RequestId, GCResult}. {type, 'major' | 'minor'}Triggers garbage collection of requested type. Default value is 'major', which would trigger a fullsweep GC. The option 'minor' is considered a hint and may lead to either minor or major GC run.If Pid equals self(), and no async option has been passed, the garbage collection is performed at once, that is, the same as calling garbage_collect/0. Otherwise a request for garbage collection is sent to the process identified by Pid, and will be handled when appropriate. If no async option has been passed, the caller blocks until GCResult is available and can be returned. GCResult informs about the result of the garbage collection request as follows: true The process identified by Pid has been garbage collected. false No garbage collection was performed, as the process identified by Pid terminated before the request could be satisfied.Notice that the same caveats apply as for garbage_collect/0. Failures: badarg If Pid is not a node local process identifier. badarg If OptionList is an invalid list of options.get() -> [{Key, Val}]TypesReturns the process dictionary as a list of {Key, Val} tuples. The items in the returned list can be in any order. Example: > put(key1, merry), put(key2, lambs), put(key3, {are, playing}), get(). [{key1,merry},{key2,lambs},{key3,{are,playing}}] get(Key) -> Val | undefinedTypesReturns the value Val associated with Key in the process dictionary, or undefined if Key does not exist. The expected time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary. Example: > put(key1, merry), put(key2, lambs), put({any, [valid, term]}, {are, playing}), get({any, [valid, term]}). {are,playing} erlang:get_cookie() -> Cookie | nocookie TypesReturns the magic cookie of the local node if the node is alive, otherwise the atom nocookie. This value is set by set_cookie/1. erlang:get_cookie(Node) -> Cookie | nocookie OTP 24.1 TypesReturns the magic cookie for node Node if the local node is alive, otherwise the atom nocookie. This value is set by set_cookie/2. get_keys() -> [Key]OTP 18.0 TypesReturns a list of all keys present in the process dictionary. The items in the returned list can be in any order. Example: > put(dog, {animal,1}), put(cow, {animal,2}), put(lamb, {animal,3}), get_keys(). [dog,cow,lamb] get_keys(Val) -> [Key]TypesReturns a list of keys that are associated with the value Val in the process dictionary. The items in the returned list can be in any order. Example: > put(mary, {1, 2}), put(had, {1, 2}), put(a, {1, 2}), put(little, {1, 2}), put(dog, {1, 3}), put(lamb, {1, 2}), get_keys({1, 2}). [mary,had,a,little,lamb] group_leader() -> pid()Returns the process identifier of the group leader for the process evaluating the function. Every process is a member of some process group and all groups have a group leader. All I/O from the group is channeled to the group leader. When a new process is spawned, it gets the same group leader as the spawning process. Initially, at system startup, init is both its own group leader and the group leader of all processes. group_leader(GroupLeader, Pid) -> trueTypesGroupLeader = Pid = pid() Sets the group leader of Pid to GroupLeader. Typically, this is used when a process started from a certain shell is to have another group leader than init. The group leader should be rarely changed in applications with a supervision tree, because OTP assumes the group leader of their processes is their application master. Setting the group leader follows the signal ordering guarantees described in the Processes Chapter in the Erlang Reference Manual. See also group_leader/0 and OTP design principles related to starting and stopping applications. halt() -> no_return()halt(Status) -> no_return()TypesThe same as halt(Status, []). Example: > halt(17). os_prompt% echo $? 17 os_prompt% halt(Status, Options) -> no_return()OTP R15B01 Status must be a non-negative integer, a string, or the atom abort. Halts the Erlang runtime system. Has no return value. Depending on Status, the following occurs: integer()The runtime system exits with integer value Status as status code to the calling environment (OS).Note On many platforms, the OS supports only status codes 0-255. A too large status code is truncated by clearing the high bits. string()An Erlang crash dump is produced with Status as slogan. Then the runtime system exits with status code 1. The string will be truncated if longer than 200 characters.Note Before ERTS 9.1 (OTP-20.1) only code points in the range 0-255 was accepted in the string. Now any unicode string is valid. abortThe runtime system aborts producing a core dump, if that is enabled in the OS.For integer Status, the Erlang runtime system closes all ports and allows async threads to finish their operations before exiting. To exit without such flushing, use Option as {flush,false}. For statuses string() and abort, option flush is ignored and flushing is not done. hd(List) -> term()TypesReturns the head of List, that is, the first element, for example: Allowed in guard tests. Failure: badarg if List is the empty list []. erlang:hibernate(Module, Function, Args) -> no_return() TypesPuts the calling process into a wait state where its memory allocation has been reduced as much as possible. This is useful if the process does not expect to receive any messages soon. The process is awaken when a message is sent to it, and control resumes in Module:Function with the arguments specified by Args with the call stack emptied, meaning that the process terminates when that function returns. Thus erlang:hibernate/3 never returns to its caller. The resume function Module:Function/Arity must be exported (Arity =:= length(Args)). If the process has any message in its message queue, the process is awakened immediately in the same way as described earlier. In more technical terms, erlang:hibernate/3 discards the call stack for the process, and then garbage collects the process. After this, all live data is in one continuous heap. The heap is then shrunken to the exact same size as the live data that it holds (even if that size is less than the minimum heap size for the process). If the size of the live data in the process is less than the minimum heap size, the first garbage collection occurring after the process is awakened ensures that the heap size is changed to a size not smaller than the minimum heap size. Notice that emptying the call stack means that any surrounding catch is removed and must be re-inserted after hibernation. One effect of this is that processes started using proc_lib (also indirectly, such as gen_server processes), are to use proc_lib:hibernate/3 instead, to ensure that the exception handler continues to work when the process wakes up. erlang:insert_element(Index, Tuple1, Term) -> Tuple2 OTP R16B Types1..tuple_size(Tuple1) + 1 Returns a new tuple with element Term inserted at position Index in tuple Tuple1. All elements from position Index and upwards are pushed one step higher in the new tuple Tuple2. Example: > erlang:insert_element(2, {one, two, three}, new).
{one,new,two,three} integer_to_binary(Integer) -> binary()OTP R16B TypesReturns a binary corresponding to the text representation of Integer, for example: > integer_to_binary(77).
<<"77">> integer_to_binary(Integer, Base) -> binary()OTP R16B Returns a binary corresponding to the text representation of Integer in base Base, for example: > integer_to_binary(1023, 16).
<<"3FF">> integer_to_list(Integer) -> string()TypesReturns a string corresponding to the text representation of Integer, for example: > integer_to_list(77).
"77" integer_to_list(Integer, Base) -> string()Returns a string corresponding to the text representation of Integer in base Base, for example: > integer_to_list(1023, 16).
"3FF" iolist_size(Item) -> integer() >= 0TypesReturns an integer, that is the size in bytes, of the binary that would be the result of iolist_to_binary(Item), for example: > iolist_size([1,2|<<3,4>>]).
4 iolist_to_binary(IoListOrBinary) -> binary()TypesReturns a binary that is made from the integers and binaries in IoListOrBinary, for example: > Bin1 = <<1,2,3>>. <<1,2,3>> > Bin2 = <<4,5>>. <<4,5>> > Bin3 = <<6>>. <<6>> > iolist_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]). <<1,2,3,1,2,3,4,5,4,6>> erlang:iolist_to_iovec(IoListOrBinary) -> iovec() OTP 20.1 TypesReturns an iovec that is made from the integers and binaries in IoListOrBinary. This function is useful when you want to flatten an iolist but you do not need a single binary. This can be useful for passing the data to nif functions such as enif_inspect_iovec or do more efficient message passing. The advantage of using this function over iolist_to_binary/1 is that it does not have to copy off-heap binaries. Example: > Bin1 = <<1,2,3>>. <<1,2,3>> > Bin2 = <<4,5>>. <<4,5>> > Bin3 = <<6>>. <<6>> %% If you pass small binaries and integers it works as iolist_to_binary > erlang:iolist_to_iovec([Bin1,1,[2,3,Bin2],4|Bin3]). [<<1,2,3,1,2,3,4,5,4,6>>] %% If you pass larger binaries, they are split and returned in a form %% optimized for calling the C function writev. > erlang:iolist_to_iovec([<<1>>,<<2:8096>>,<<3:8096>>]). [<<1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,...>>, <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, ...>>, <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...>>] is_alive() -> boolean()is_atom(Term) -> boolean()TypesReturns true if Term is an atom, otherwise false. Allowed in guard tests. is_binary(Term) -> boolean()TypesReturns true if Term is a binary, otherwise false. A binary always contains a complete number of bytes. Allowed in guard tests. is_bitstring(Term) -> boolean()TypesReturns true if Term is a bitstring (including a binary), otherwise false. Allowed in guard tests. is_boolean(Term) -> boolean()TypesReturns true if Term is the atom true or the atom false (that is, a boolean). Otherwise returns false. Allowed in guard tests. erlang:is_builtin(Module, Function, Arity) -> boolean() TypesThis BIF is useful for builders of cross-reference tools. Returns true if Module:Function/Arity is a BIF implemented in C, otherwise false. is_float(Term) -> boolean()TypesReturns true if Term is a floating point number, otherwise false. Allowed in guard tests. is_function(Term) -> boolean()TypesReturns true if Term is a fun, otherwise false. Allowed in guard tests. is_function(Term, Arity) -> boolean()TypesReturns true if Term is a fun that can be applied with Arity number of arguments, otherwise false. Allowed in guard tests. is_integer(Term) -> boolean()TypesReturns true if Term is an integer, otherwise false. Allowed in guard tests. is_list(Term) -> boolean()TypesReturns true if Term is a list with zero or more elements, otherwise false. Allowed in guard tests. is_map(Term) -> boolean()OTP 17.0 TypesReturns true if Term is a map, otherwise false. Allowed in guard tests. is_map_key(Key, Map) -> boolean()OTP 21.0 TypesReturns true if map Map contains Key and returns false if it does not contain the Key. The call fails with a {badmap,Map} exception if Map is not a map. Example: > Map = #{"42" => value}. #{"42" => value} > is_map_key("42",Map). true > is_map_key(value,Map). false Allowed in guard tests. is_number(Term) -> boolean()TypesReturns true if Term is an integer or a floating point number. Otherwise returns false. Allowed in guard tests. is_pid(Term) -> boolean()TypesReturns true if Term is a process identifier, otherwise false. Allowed in guard tests. is_port(Term) -> boolean()TypesReturns true if Term is a port identifier, otherwise false. Allowed in guard tests. is_process_alive(Pid) -> boolean()TypesPid must refer to a process at the local node. Returns true if the process exists and is alive, that is, is not exiting and has not exited. Otherwise returns false. If process P1 calls is_process_alive(P2Pid) it is guaranteed that all signals, sent from P1 to P2 (P2 is the process with identifier P2Pid) before the call, will be delivered to P2 before the aliveness of P2 is checked. This guarantee means that one can use is_process_alive/1 to let a process P1 wait until a process P2, which has got an exit signal with reason kill from P1, is killed. Example: exit(P2Pid, kill), % P2 might not be killed is_process_alive(P2Pid), % P2 is not alive (the call above always return false) See the documentation about signals and erlang:exit/2 for more information about signals and exit signals. is_record(Term, RecordTag) -> boolean()TypesReturns true if Term is a tuple and its first element is RecordTag. Otherwise returns false. Note Normally the compiler treats calls to is_record/2 especially. It emits code to verify that Term is a tuple, that its first element is RecordTag, and that the size is correct. However, if RecordTag is not a literal atom, the BIF is_record/2 is called instead and the size of the tuple is not verified. Allowed in guard tests, if RecordTag is a literal atom. is_record(Term, RecordTag, Size) -> boolean()TypesRecordTag must be an atom. Returns true if Term is a tuple, its first element is RecordTag, and its size is Size. Otherwise returns false. Allowed in guard tests if RecordTag is a literal atom and Size is a literal integer. Note This BIF is documented for completeness. Usually is_record/2 is to be used. is_reference(Term) -> boolean()TypesReturns true if Term is a reference, otherwise false. Allowed in guard tests. is_tuple(Term) -> boolean()TypesReturns true if Term is a tuple, otherwise false. Allowed in guard tests. length(List) -> integer() >= 0TypesReturns the length of List, for example: > length([1,2,3,4,5,6,7,8,9]).
9 Allowed in guard tests. link(PidOrPort) -> trueTypesSets up and activates a link between the calling process and another process or a port identified by PidOrPort. We will from here on call the identified process or port linkee. If the linkee is a port, it must reside on the same node as the caller. If one of the participants of a link terminates, it will send an exit signal to the other participant. The exit signal will contain the exit reason of the terminated participant. Other cases when exit signals are triggered due to a link are when no linkee exist (noproc exit reason) and when the connection between linked processes on different nodes is lost or cannot be established (noconnection exit reason). An existing link can be removed by calling unlink/1. For more information on links and exit signals due to links, see the Processes chapter in the Erlang Reference Manual:
For historical reasons, link/1 has a strange semi-synchronous behavior when it is "cheap" to check if the linkee exists or not, and the caller does not trap exits. If the above is true and the linkee does not exist, link/1 will raise a noproc error exception. The expected behavior would instead have been that link/1 returned true, and the caller later was sent an exit signal with noproc exit reason, but this is unfortunately not the case. The noproc exception is not to be confused with an exit signal with exit reason noproc. Currently it is "cheap" to check if the linkee exists when it is supposed to reside on the same node as the calling process. The link setup and activation is performed asynchronously. If the link already exists, or if the caller attempts to create a link to itself, nothing is done. A detailed description of the link protocol can be found in the Distribution Protocol chapter of the ERTS User's Guide. Failure:
list_to_atom(String) -> atom()TypesReturns the atom whose text representation is String. As from Erlang/OTP 20, String may contain any Unicode character. Earlier versions allowed only ISO-latin-1 characters as the implementation did not allow Unicode characters above 255. Example: > list_to_atom("Erlang").
'Erlang' list_to_binary(IoList) -> binary()TypesReturns a binary that is made from the integers and binaries in IoList, for example: > Bin1 = <<1,2,3>>. <<1,2,3>> > Bin2 = <<4,5>>. <<4,5>> > Bin3 = <<6>>. <<6>> > list_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]). <<1,2,3,1,2,3,4,5,4,6>> list_to_bitstring(BitstringList) -> bitstring()TypesBitstringList = bitstring_list() Returns a bitstring that is made from the integers and bitstrings in BitstringList. (The last tail in BitstringList is allowed to be a bitstring.) Example: > Bin1 = <<1,2,3>>. <<1,2,3>> > Bin2 = <<4,5>>. <<4,5>> > Bin3 = <<6,7:4>>. <<6,7:4>> > list_to_bitstring([Bin1,1,[2,3,Bin2],4|Bin3]). <<1,2,3,1,2,3,4,5,4,6,7:4>> list_to_existing_atom(String) -> atom()TypesReturns the atom whose text representation is String, but only if there already exists such atom. An atom exists if it has been created by the run-time system by either loading code or creating a term in which the atom is part. Failure: badarg if there does not already exist an atom whose text representation is String. Note Note that the compiler may optimize away atoms. For example, the compiler will rewrite atom_to_list(some_atom) to "some_atom". If that expression is the only mention of the atom some_atom in the containing module, the atom will not be created when the module is loaded, and a subsequent call to list_to_existing_atom("some_atom") will fail. list_to_float(String) -> float()TypesReturns the float whose text representation is String, for example: > list_to_float("2.2017764e+0").
2.2017764 The float string format is the same as the format for Erlang float literals except for that underscores are not permitted. Failure: badarg if String contains a bad representation of a float. list_to_integer(String) -> integer()TypesReturns an integer whose text representation is String, for example: > list_to_integer("123").
123 > list_to_integer("-123").
-123 > list_to_integer("+123234982304982309482093833234234").
123234982304982309482093833234234 String must contain at least one digit character and can have an optional prefix consisting of a single "+" or "-" character (that is, String must match the regular expression "^[+-]?[0-9]+$"). Failure: badarg if String contains a bad representation of an integer. list_to_integer(String, Base) -> integer()Returns an integer whose text representation in base Base is String, for example: > list_to_integer("3FF", 16).
1023 > list_to_integer("+3FF", 16).
1023 > list_to_integer("3ff", 16).
1023 > list_to_integer("3fF", 16).
1023 > list_to_integer("-3FF", 16).
-1023 For example, when Base is 16, String must match the regular expression "^[+-]?([0-9]|[A-F]|[a-f])+$". Failure: badarg if String contains a bad representation of an integer. list_to_pid(String) -> pid()TypesReturns a process identifier whose text representation is a String, for example: > list_to_pid("<0.4.1>").
<0.4.1>
Failure: badarg if String contains a bad representation of a process identifier. Warning This BIF is intended for debugging and is not to be used in application programs. list_to_port(String) -> port()OTP 20.0 TypesReturns a port identifier whose text representation is a String, for example: > list_to_port("#Port<0.4>").
#Port<0.4> Failure: badarg if String contains a bad representation of a port identifier. Warning This BIF is intended for debugging and is not to be used in application programs. list_to_ref(String) -> reference()OTP 20.0 TypesReturns a reference whose text representation is a String, for example: > list_to_ref("#Ref<0.4192537678.4073193475.71181>").
#Ref<0.4192537678.4073193475.71181> Failure: badarg if String contains a bad representation of a reference. Warning This BIF is intended for debugging and is not to be used in application programs. list_to_tuple(List) -> tuple()TypesReturns a tuple corresponding to List, for example > list_to_tuple([share, ['Ericsson_B', 163]]).
{share, ['Ericsson_B', 163]} List can contain any Erlang terms. load_module(Module, Binary) -> {module, Module} | {error, Reason}TypesReason = If Binary contains the object code for module Module, this BIF loads that object code. If the code for module Module already exists, all export references are replaced so they point to the newly loaded code. The previously loaded code is kept in the system as old code, as there can still be processes executing that code. Returns either {module, Module}, or {error, Reason} if loading fails. Reason is one of the following: badfileThe object code in Binary has an incorrect format or the object code contains code for another module than Module. not_purged Binary contains a module that cannot be loaded because old code for this module already exists. on_loadThe code in Binary contains an on_load declaration that must be executed before Binary can become the current code. Any previous current code for Module will remain until the on_load call has finished. not_allowedThe code in Binary has been compiled with features that are currently not enabled in the runtime system.Warning This BIF is intended for the code server (see code(3)) and is not to be used elsewhere. erlang:load_nif(Path, LoadInfo) -> ok | Error TypesError = {error, {Reason, Text :: string()}} Reason = Loads and links a dynamic library containing native implemented functions (NIFs) for a module. Path is a file path to the shareable object/dynamic library file minus the OS-dependent file extension (.so for Unix and .dll for Windows). Notice that on most OSs the library has to have a different name on disc when an upgrade of the nif is done. If the name is the same, but the contents differ, the old library may be loaded instead. For information on how to implement a NIF library, see erl_nif(3). LoadInfo can be any term. It is passed on to the library as part of the initialization. A good practice is to include a module version number to support future code upgrade scenarios. The call to load_nif/2 must be made directly from the Erlang code of the module that the NIF library belongs to. It returns either ok, or {error,{Reason,Text}} if loading fails. Reason is one of the following atoms while Text is a human readable string that can give more information about the failure: load_failedThe OS failed to load the NIF library. bad_libThe library did not fulfill the requirements as a NIF library of the calling module. load | upgrade The corresponding library callback was unsuccessful. reloadA NIF library is already loaded for this module instance. The previously deprecated reload feature was removed in OTP 20. old_codeThe call to load_nif/2 was made from the old code of a module that has been upgraded; this is not allowed.If the -nifs() attribute is used (which is recommended), all NIFs in the dynamic library much be declared as such for load_nif/2 to succeed. On the other hand, all functions declared with the -nifs() attribute do not have to be implemented by the dynamic library. This allows a target independent Erlang file to contain fallback implementations for functions that may lack NIF support depending on target OS/hardware platform. erlang:loaded() -> [Module] TypesReturns a list of all loaded Erlang modules (current and old code), including preloaded modules. See also code(3). erlang:localtime() -> DateTime TypesReturns the current local date and time, {{Year, Month, Day}, {Hour, Minute, Second}}, for example: > erlang:localtime().
{{1996,11,6},{14,45,17}} The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time. erlang:localtime_to_universaltime(Localtime) -> Universaltime TypesConverts local date and time to Universal Time Coordinated (UTC), if supported by the underlying OS. Otherwise no conversion is done and Localtime is returned. Example: > erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}).
{{1996,11,6},{13,45,17}} Failure: badarg if Localtime denotes an invalid date and time. erlang:localtime_to_universaltime(Localtime,
IsDst) -> TypesIsDst = true | false | undefined Converts local date and time to Universal Time Coordinated (UTC) as erlang:localtime_to_universaltime/1, but the caller decides if Daylight Saving Time is active. If IsDst == true, Localtime is during Daylight Saving Time, if IsDst == false it is not. If IsDst == undefined, the underlying OS can guess, which is the same as calling erlang:localtime_to_universaltime(Localtime). Examples: > erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, true). {{1996,11,6},{12,45,17}} > erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, false). {{1996,11,6},{13,45,17}} > erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, undefined). {{1996,11,6},{13,45,17}} Failure: badarg if Localtime denotes an invalid date and time. make_ref() -> reference()Returns a unique reference. The reference is unique among connected nodes. Warning Before OTP-23 when a node is restarted multiple times with the same node name, references created on a newer node can be mistaken for a reference created on an older node with the same node name. erlang:make_tuple(Arity, InitialValue) -> tuple() TypesCreates a new tuple of the specified Arity, where all elements are InitialValue, for example: > erlang:make_tuple(4, []).
{[],[],[],[]} erlang:make_tuple(Arity, DefaultValue, InitList) -> tuple() TypesCreates a tuple of size Arity, where each element has value DefaultValue, and then fills in values from InitList. Each list element in InitList must be a two-tuple, where the first element is a position in the newly created tuple and the second element is any term. If a position occurs more than once in the list, the term corresponding to the last occurrence is used. Example: > erlang:make_tuple(5, [], [{2,ignored},{5,zz},{2,aa}]).
{[],aa,[],[],zz} map_get(Key, Map) -> ValueOTP 21.0 TypesReturns value Value associated with Key if Map contains Key. The call fails with a {badmap,Map} exception if Map is not a map, or with a {badkey,Key} exception if no value is associated with Key. Example: > Key = 1337, Map = #{42 => value_two,1337 => "value one","a" => 1}, map_get(Key,Map). "value one" Allowed in guard tests. map_size(Map) -> integer() >= 0OTP 17.0 TypesReturns an integer, which is the number of key-value pairs in Map, for example: > map_size(#{a=>1, b=>2, c=>3}).
3 Allowed in guard tests. erlang:match_spec_test(MatchAgainst, MatchSpec, Type) -> OTP 19.0 TypesType = table | trace TestResult = Tests a match specification used in calls to ets:select/2 and erlang:trace_pattern/3. The function tests both a match specification for "syntactic" correctness and runs the match specification against the object. If the match specification contains errors, the tuple {error, Errors} is returned, where Errors is a list of natural language descriptions of what was wrong with the match specification. If Type is table, the object to match against is to be a tuple. The function then returns {ok,Result,[],Warnings}, where Result is what would have been the result in a real ets:select/2 call, or false if the match specification does not match the object tuple. If Type is trace, the object to match against is to be a list. The function returns {ok, Result, Flags, Warnings}, where Result is one of the following:
Flags is a list containing all the trace flags to be enabled, currently this is only return_trace. This is a useful debugging and test tool, especially when writing complicated match specifications. See also ets:test_ms/2. max(Term1, Term2) -> MaximumTypesTerm1 = Term2 = Maximum = term() Returns the largest of Term1 and Term2. If the terms compare equal with the == operator, Term1 is returned. The Expressions section contains descriptions of the == operator and how terms are ordered. Examples: erlang:md5(Data) -> Digest TypesComputes an MD5 message digest from Data, where the length of the digest is 128 bits (16 bytes). Data is a binary or a list of small integers and binaries. For more information about MD5, see RFC 1321 - The MD5 Message-Digest Algorithm. Warning The MD5 Message-Digest Algorithm is not considered safe for code-signing or software-integrity purposes. erlang:md5_final(Context) -> Digest TypesFinishes the update of an MD5 Context and returns the computed MD5 message digest. erlang:md5_init() -> Context TypesCreates an MD5 context, to be used in the following calls to md5_update/2. erlang:md5_update(Context, Data) -> NewContext TypesUpdate an MD5 Context with Data and returns a NewContext. erlang:memory() -> [{Type, Size}] TypesType = memory_type() memory_type() = Returns a list with information about memory dynamically allocated by the Erlang emulator. Each list element is a tuple {Type, Size}. The first element Type is an atom describing memory type. The second element Size is the memory size in bytes. Memory types: totalThe total amount of memory currently allocated. This is the same as the sum of the memory size for processes and system. processesThe total amount of memory currently allocated for the Erlang processes. processes_usedThe total amount of memory currently used by the Erlang processes. This is part of the memory presented as processes memory. systemThe total amount of memory currently allocated for the emulator that is not directly related to any Erlang process. Memory presented as processes is not included in this memory. instrument(3) can be used to get a more detailed breakdown of what memory is part of this type. atomThe total amount of memory currently allocated for atoms. This memory is part of the memory presented as system memory. atom_usedThe total amount of memory currently used for atoms. This memory is part of the memory presented as atom memory. binaryThe total amount of memory currently allocated for binaries. This memory is part of the memory presented as system memory. codeThe total amount of memory currently allocated for Erlang code. This memory is part of the memory presented as system memory. etsThe total amount of memory currently allocated for ETS tables. This memory is part of the memory presented as system memory. maximumThe maximum total amount of memory allocated since the emulator was started. This tuple is only present when the emulator is run with instrumentation. For information on how to run the emulator with instrumentation, see instrument(3) and/or erl(1). Note The system value is not complete. Some allocated memory that is to be part of this value is not. When the emulator is run with instrumentation, the system value is more accurate, but memory directly allocated for malloc (and friends) is still not part of the system value. Direct calls to malloc are only done from OS-specific runtime libraries and perhaps from user-implemented Erlang drivers that do not use the memory allocation functions in the driver interface. As the total value is the sum of processes and system, the error in system propagates to the total value. The different amounts of memory that are summed are not gathered atomically, which introduces an error in the result. The different values have the following relation to each other. Values beginning with an uppercase letter is not part of the result. total = processes + system processes = processes_used + ProcessesNotUsed system = atom + binary + code + ets + OtherSystem atom = atom_used + AtomNotUsed RealTotal = processes + RealSystem RealSystem = system + MissedSystem More tuples in the returned list can be added in a future release. Note The total value is supposed to be the total amount of memory dynamically allocated by the emulator. Shared libraries, the code of the emulator itself, and the emulator stacks are not supposed to be included. That is, the total value is not supposed to be equal to the total size of all pages mapped to the emulator. Also, because of fragmentation and prereservation of memory areas, the size of the memory segments containing the dynamically allocated memory blocks can be much larger than the total size of the dynamically allocated memory blocks. Note As from ERTS 5.6.4, erlang:memory/0 requires that all erts_alloc(3) allocators are enabled (default behavior). Failure: notsup if an erts_alloc(3) allocator has been disabled. erlang:memory(TypeList :: [memory_type()]) -> Typesmemory_type() = Returns the memory size in bytes allocated for memory of type Type. The argument can also be specified as a list of memory_type() atoms, in which case a corresponding list of {memory_type(), Size :: integer >= 0} tuples is returned. Note As from ERTS 5.6.4, erlang:memory/1 requires that all erts_alloc(3) allocators are enabled (default behavior). Failures: badarg If Type is not one of the memory types listed in the description of erlang:memory/0. badarg If maximum is passed as Type and the emulator is not run in instrumented mode. notsup If an erts_alloc(3) allocator has been disabled.See also erlang:memory/0. min(Term1, Term2) -> MinimumTypesTerm1 = Term2 = Minimum = term() Returns the smallest of Term1 and Term2. If the terms compare equal with the == operator, Term1 is returned. The Expressions section contains descriptions of the == operator and how terms are ordered. Examples: module_loaded(Module) -> boolean()TypesReturns true if the module Module is loaded, otherwise false. It does not attempt to load the module. Warning This BIF is intended for the code server (see code(3)) and is not to be used elsewhere. monitor(Type :: process, Item :: monitor_process_identifier()) -> |