run erlang code cause crash

7 views
Skip to first unread message

Kai Ding

unread,
Apr 24, 2017, 5:26:48 AM4/24/17
to Erlang Questions
Hi, all

      I'm a freshman to erlang, and working hard. When run a example as below, it crashes:
-module(fac).
-export([fac_list/1,element/1]).

element(1) -> 1;
element(2) -> 1;
element(N) -> element(N-1) + element(N-2).

fac_list(N) -> fac_list([], N).

fac_list(L, 0) -> L;
fac_list(L, N) -> fac_list([element(N)|L], N-1).

after comple it, i got error like:
dingkaideMacBook-Pro:erlang dingkai$ erl -s fac fac 3
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

{"init terminating in do_boot",{undef,[{fac,fac,[['3']],[]},{init,start_em,1,[]},{init,do_boot,3,[]}]}}
init terminating in do_boot ()

Crash dump is being written to: erl_crash.dump...done

i am a little confused~

7stud

unread,
May 20, 2017, 7:07:06 AM5/20/17
to Erlang Questions
Integers on the command get passed to your program as atoms.  You can't take the factorial of an atom.  You need to convert the atom to an int.  In the following code when you read 'list' think 'string':

-module(fac).
-export([setup/1]).


setup([Atom]) ->
    timer:sleep(500),
    io:format("From command line: ~w~n", [Atom]),

    Int = list_to_integer(atom_to_list(Atom)),
    Result = fac_list(Int),

    io:format("Factorial of ~w is: ~w~n", [Int, Result]),
    init:stop().


fac_list(N) -> fac_list([], N).

fac_list(L, 0) -> L;
fac_list(L, N) -> fac_list([my_element(N)|L], N-1).

my_element(1) -> 1;
my_element(2) -> 1;
my_element(N) -> my_element(N-1) + my_element(N-2).


Reply all
Reply to author
Forward
0 new messages