I’m a total beginner to Erlang so I’m getting stuck with some very basic syntax stuff. Apologies for my ineptitude.
I have a string input and I need to get each character. To start with though I am not able to log anything. It crashes on the io.format
. This is obviously not a valid approach to this.
[H|T] = "UDDDUDUU",
io:format(H). % sigils didn't seem to help either
counter(0, [H|T])
{"init terminating in do_boot",{badarg,[{io,format,"U",[{file,"io.erl"},{line,99},{error_info,#{cause=>{device,put_chars},module=>erl_stdlib_errors}}]},{init,start_em,1,[]},{init,do_boot,3,[]}]}}
init terminating in do_boot ({badarg,[{io,format,U,[{_},{_},{_}]},{init,start_em,1,[]},{init,do_boot,3,[]}]})
Further investigation shows this. In learnyousomeerlang it talks about this issue but doesn’t clearly show how to handle it (not clearly to me). I’m not sure if this is the reason it is crashing, the fact that it’s an int
and not a char,
but it probably doesn’t help.
2> [H|_] = "UDDDUDUU".
"UDDDUDUU"
3> H.
85
So would I do this? How would I iterate through a string? Or convert it to a list of separated values? I’m looking for the conventional way to do this.
The overall gist is something like this, but it doesn’t work. Any attempt to log Head
crashes it.
counter(Count, []) ->
Count;
counter(Count, [Head|Tail]) ->
# this comparison does not work - how would I do this?
case Head =:= "D" of
true ->
io:format("D"),
counter(Count - 1, Tail);
false ->
io:format("U"),
counter(Count + 1, Tail)
end.
start() ->
[H|T] = "UDDDUDUU",
counter(0, [H|T]).