避免在Erlang中将数字转换为字符

nhjlsmyf  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(211)

I am 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) ).

mpgws1up

mpgws1up1#

如果你看一下注解,你会发现shell打印数据的方式比数据本身更有问题。你的逻辑是正确的,我不会改变它。你可以在代码中引入一些io:format/2的用法,但我想这会使在代码的其他部分使用这个函数变得更困难。
另一种方法是改变shell设置本身。有shell:strings/1函数可以禁止将列表打印为字符串,它应该完全按照你的要求来做。只要记住在你完成shell的东西后把它改回来,因为当你开始使用一些“字符串”返回函数时,它可能会引入一些混乱。

相关问题