Avoid converting numbers to characters in erlang

2019-01-15 16:53发布

I'm having trouble with erlang converting listed numbers to characters whenever none of the listed items could not also be representing a character.

I am writing a function to separate all the numbers in a positive integer and put them in a list, for example: digitize(123) should return [1,2,3] and so on.

The following code works fine, except when the list only consist of 8's and/or 9's:

digitize(_N) when _N =:= 0 -> [];
digitize(_N) when _N > 0 -> _H = [_N rem 10], _T = digitize(_N div 10), _T ++ _H.

For example: Instead of digitize(8) returning [8], it gives me the nongraphic character "\b" and digitize(89) returns "\b\t". This is only for numbers 8 and 9 and when they're put alone inside the list. digitize(891) will correctly return [8,9,1] for example.

I am aware of the reason for this but how can I solve it without altering my result? (ex: to contain empty lists inside the result like [[],[8]] for digitize(8))

1条回答
叛逆
2楼-- · 2019-01-15 17:29

If you look at comments you will see that it is more problem of the way shell prints your data, than the data itself. You logic is wright and I would not change it. You could introduce some use of io:format/2 into you code, but I guess that it would make it harder to use this function in other parts of code.

Other way around it is changing the shell settings itself. There is shell:stings/1 functions that disables printing lists as stings, and it should do exactly what you want. Just remember to change it back when you finish with your shell stuff, since it could introduce some confusion when you will start using some "string" returning functions.

查看更多
登录 后发表回答