Hello World (Erlang)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

Every Erlang program begins with a module declaration.

<<module>>=
-module(hello).

The module declaration exists to provide a name space for any symbols you define without risk of collision with others and an obfuscatory layer for functions you don't wish others to use.

Once the module is set, the next thing we need to do is decide which functions we want the outside world to see. We do this with an export statement.

<<exports>>=
-export([hello/0]).

The export statement is given a list of functions exported by the module in the form of name/arity. Other modules can only access the functions in this module if they have been placed in the export statement. In our "hello world" module we only want to expose the function that says "hello". It is, conveniently, the only function.

Now we add the actual function.

<<hello.erl>>=
module
exports
hello() -> io:format("Hello, world!~n").

The function is given in the form of name(arguments) -> body. The body of this function consists entirely of a single function call. The function call there is given in the form of module:function(arguments). Thus we are calling the format function in the io module. (This is one of the standard modules and functions provided in the Erlang environment.)

Download code
Views
Personal tools