Simon
Simon

Reputation: 59

Why is badarg displayed in Erlang?

This is my Erlang code:

-module(solarSystem). 
-export([process_csv/1,is_numeric/1]). 
is_numeric(L) -> 
S = trim(L,""), 
Float = (catch erlang:list_to_float( S)), 
Int = (catch erlang:list_to_integer(S)), 
is_number(Float) orelse is_number(Int). 
trim([],A)->A; 
trim([32|T],A)->trim(T,A); 
trim([H|T],A)->trim(T,A++[H]). 
process_csv([_H|T]) -> process_line(T, ""). 
process_line([], A) -> A; 
process_line([H|T], A) -> 
process_line(T, A ++ deal(H, "", 1)). 
deal([], B, _Count) -> B ++ "\n"; 
deal([H|T], B, Count) -> 
if (H == "planets ") -> 
deal([], planetcheck([H|T], "", 1), Count); 
true -> 
case is_numeric(H) of 
true -> if Count == 6 -> 
deal([], B ++ subcheck([H|T], "", 6) ++ "];", Count+1); 
true -> 
deal(T, B ++ H ++ ",", Count+1) 
end; 
false -> if Count == 2 -> 
deal(T, B ++ "=[\"" ++ H ++ "\",", Count+1); 
true -> 
deal(T, B ++ H, Count+1) 
end 
end 
end. 
subcheck([], C, _Scount) -> C; 
subcheck([H|T], C, Scount) -> 
case is_numeric(H) of 
true -> if (Scount == 6) and (T == []) -> 
subcheck(T, C ++ H ++ ",[]", Scount+1); 
true -> 
subcheck([], C ++ H ++ "," ++ noone(T, C), Scount+1) 
end; 
false -> if T == [] -> 
subcheck(T, C ++ H ++ "]", Scount+1); 
true -> 
subcheck(T, C ++ H ++ ",", Scount+1) 
end 
end. 
noone([], D) -> D; 
noone([H|T], D) -> 
case is_numeric(H) of 
true -> 
noone([], D ++ T); 
false -> 
if T == [] -> 
subcheck(T, D ++ "["++ H, 7); 
true -> 
subcheck(T, D ++ "["++ H ++ ",", 7) 
end 
end. 
planetcheck([], E, _Pcount) -> E ++ "];"; 
planetcheck([H|T], E, Pcount) -> 
if Pcount == 1 -> 
planetcheck(T, E ++ H ++ "=[", Pcount+1); 
true -> 
if T == "" -> 
planetcheck(T, E ++ H, Pcount+1); 
true -> 
planetcheck(T, E ++ H ++ ",", Pcount+1) 
end 
end.

This is the main code (another file which will run my code):

#!/usr/bin/env escript
%-module(main).
%-export([main/1, print_list/1, usage/0]).
%% -*- erlang -*-
%%! -smp enable -sname factorial -mnesia debug verbose
main([String]) ->
    try
        CSV = csv:parse_file(String),
        F =solarSystem:process_csv(CSV),
        print_list(F)
    catch
        A:B -> io:format("~w : ~w~n",[A,B]),
        usage()
    end;
main(_) ->
    usage().

print_list([])-> [];
print_list([H|T])->io:format("~s~n",[H]),print_list(T).

usage() ->
    io:format("usage: escript main.erl <filename>\n"),
    halt(1).

The error was caused by reopening VSCode, but the error didn't appear yesterday while I opened a previous one. I am able to run it without compiling the main function before I close VSCode. The image shows the error.

enter image description here

Upvotes: 0

Views: 230

Answers (1)

Roger Lipscombe
Roger Lipscombe

Reputation: 91945

Your use of try and catch is hiding the error. Remove it and Erlang will tell you exactly where the error's coming from. If you don't want to do that, use catch A:B:S. S is the stack trace; print that out.

Upvotes: 3

Related Questions