Erlang Central

Hello World

Revision as of 06:59, 4 April 2007 by Ayrnieu (Talk | contribs)

Problem

You want to write the classic "Hello World!" program in Erlang.

Solution

This is very impractical in Erlang, but here you go:

$ erl -noshell -eval 'io:fwrite("Hello, world!\n"), init:stop().'
Hello, world!
$

Alternatively, you can use escript from R11B-4. This is probably what you really want, but please read below before getting too disappointed with escript's start-up delay.

$ cat hello                                                                                             
#! /usr/bin/env escript
main(_) -> io:fwrite("Hello, world!\n").
$ ./hello
Hello, world!
$ 

Discussion

To explain the above, I quote Erik Naggum's comments on comp.lang.lisp

  The famous C program is famous for its ablity to produce an executable
  with a minimal amount of fuss.  It really shows off the Unix environment,
  and not the language.  However, an executable is only a funtcion that
  resides on disk in the Unix file sysem and which you call from the
  shell's read-execute interactive loop.  Common Lisp systems offer their
  own interactive loop, called the read-eval-print loop and do not
  generally take part in the shell interactive loop the same way other
  languages do.  Some find this a insurmountable obstacle to using Common
  Lisp, others love it.  However, the code for the core program is simple: 

Erlang has a similar situation to that of Common Lisp (also: Smalltalk), although Erlang's is mitigated by its nodes, which are more easily thought of as little operating systems. But to make it clear: In Erlang you do not start a program from the unix shell, let it run its course, and then have it exit. Rather, you start one or many nodes and run programs within them. But if you'd like an example to show off the Erlang environment rather than the language:

-module(hello).
-export([hello/0]).

hello() -> io:fwrite("Hello, world!\n").
(mischief@mordor)199> cd("/foo/bar/baz").
/foo/bar/baz
(mischief@mordor)200> c(hello).
{ok,hello}
(mischief@mordor)201> hello:hello().
Hello, world!
ok
(mischief@mordor)202>

Alternatively, you could compile hello.erl separately:

$ erlc hello.erl
(mischief@mordor)199> code:add_pathz("/foo/bar/baz").
true
(mischief@mordor)200> hello:hello().
Hello, world!
(mischief@mordor)201>

This is a quicker cycle that it might seem, here, and there's much more of interest in the environment than shown off, here. Just know that many people consider that the advantages of Erlang far outweigh not having the cute little unix executables celebrated by 'hello world' examples. This does constrain the sort of programs that you can sensibly write in Erlang, but so also are other languages constrained by not having Erlang nodes :-)