English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Erlang-Basisgrammatik

To understand the basic syntax of Erlang, let's first look at a simpleHello WorldProgram.

Beispiel

%Hello World-Programm
-module(helloworld). 
-export([start/0]). 
start() -> 
   io:fwrite("Hello, world!\n").

The following points should be noted about the above program:

  • The % symbol is used to add comments to the program.

  • The module statement is like adding a command space in any programming language. Here, we should mention that this code will be part of a module named helloworld.

  • You can use the export function to use any function defined in the program. We are defining a function named start, and in order to use the start function, we must use the export statement./0 represents that our function 'start' accepts 0 parameters.

  • 我们最终定义了start函数。这里我们使用另一个名为io的模块,它在Erlang中具有所有必需的输入输出函数。我们使用fwrite函数将“Hello World”输出到控制台。

上面程序的输出将是-

输出

Hello, world!

声明的一般形式

在Erlang中,您已经看到Erlang语言中使用了不同的符号。让我们看一下我们从一个简单的Hello World程序中看到的内容-

  • 连字符(–)通常与模块,导入和导出语句一起使用。连字符用于为每个语句赋予相应的含义。因此,Hello world程序的示例显示在以下程序中-

-module(helloworld).
-export([start/0]).

每个语句都用点(.)符号定界。Erlang中的每个语句都需要以该定界符结尾。Hello world程序的示例如下例所示:

io:fwrite("Hello, world!\n").
  • 斜杠(/)符号与函数一起使用,以定义函数接受的参数数量。

-export([start/0]).

模块

在Erlang中,所有代码都分为模块。模块由一系列属性和函数声明组成。就像其他编程语言中的名称空间的概念一样,该名称空间用于逻辑上分离不同的代码单元。

定义模块

使用模块标识符定义模块。通用语法和示例如下。

语法

-module(ModuleName)

ModuleName需求是相同的文件名减去扩展.erl。否则,代码加载将无法按预期进行。

Beispiel

-module(helloworld)

这些模块将在随后的章节中详细介绍,这只是为了使您对如何定义模块有一个基本的了解。

Erlang中的导入声明

在Erlang中,如果要使用现有Erlang模块的功能,则可以使用import语句。以下程序描述了import语句的一般形式-

Beispiel

-import (modulename, [functionname/parameter]).

在哪里,

  • 模块名−这是需要导入的模块的名称。

  • 函数名称/参数 −模块中需要导入的功能。

让我们更改编写hello world程序以使用import语句的方式。该示例将在以下程序中显示。

Beispiel

%Hello World-Programm
-module(helloworld).
-import(io,[fwrite/1]).
-export([start/0]).
start() ->
   fwrite("Hello, world!\n").

在上面的代码中,我们使用import关键字导入库“ io”,尤其是fwrite函数。因此,现在无论何时调用fwrite函数,都不必在任何地方都提及io模块名称。

Erlang中的关键字

Schlüsselwörter sind reservierte Wörter in Erlang und dürfen nicht für andere als vorgesehene Zwecke verwendet werden. Hier ist die Liste der Schlüsselwörter in Erlang.

afterandandalsoband
beginbnotborbsl
bsrbxorcasecatch
conddivendfun
ifletnotof
ororelsereceiverem
trywhenxor

Erlang-Kommentare

Kommentare werden verwendet, um den Code zu dokumentieren. Einzeilige Kommentare werden durch den Symbol % an jeder Stelle in der Zeile markiert. Hier ist der gleiche-

Beispiel

%Hello World-Programm
-module(helloworld).
%Importiere Funktion, um den io-Modul zu importieren
-import(io,[fwrite/1]).
%Exportiere Funktion, um sicherzustellen, dass auf die Startfunktion zugegriffen werden kann.
-export([start/0]).
start() ->
   fwrite("Hello, world!\n").