[erlang-questions] output [[[[]|2]|1]|0] instead of [2.1.0]

Roelof Wobben r.wobben@REDACTED
Tue Feb 10 16:05:12 CET 2015


Roelof Wobben schreef op 10-2-2015 om 15:58:
> Loïc Hoguin schreef op 10-2-2015 om 15:45:
>> On 02/10/2015 03:42 PM, Loïc Hoguin wrote:
>>> You are creating what is called an improper list.
>>>
>>> This is a proper list:
>>>
>>> [1,2,3]
>>>
>>> This is the same list using the | operator:
>>>
>>> [1|[2|[3]]]
>>>
>>> Now what happens if you write this, for example?
>>>
>>> [1,2|3]
>>>
>>> It still works. This is called an improper list. An improper list is a
>>> list where the tail is not a list.
>>
>> Forgot to say that most lists functions expect proper lists and will 
>> fail when they encounter an improper list, including the length/1 
>> function.
>>
>> Cheers.
>>
>>> When you do A++B Erlang will only ensure that A is a list. B can be
>>> anything. If it's not a list, however, then you end up with an improper
>>> list.
>>>
>>> I advise you to avoid ++ when doing most list related exercices, go 
>>> with
>>> the | operator instead.
>>>
>>> On 02/10/2015 03:19 PM, Roelof Wobben wrote:
>>>> Hello,
>>>>
>>>> I have to make a reversed list to a number so reverse_list(2) will
>>>> output [2.1]
>>> ...
>>>
>>
>
> Hello,
>
> Thanks both for the explanation.
> I will rewrite the code to use | instead of ++
>
> Roelof
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

Then I hope this solution is well written :

-module(list_creation).

-export([create/1, create_reverse/1]).

create(Number) when Number > 0 ->
   create_acc(Number,[]).

create_acc(0,Acc) ->
   Acc;

create_acc(Number, Acc) ->
   create_acc(Number -1, [Number | Acc]).

create_reverse(Number) when Number > 0 ->
   create_reverse_acc(Number, 1, []).

create_reverse_acc(Endnumber, Endnumber, Acc) ->
   [Endnumber | Acc ];

create_reverse_acc(Endnumber,Current, Acc) ->
     create_reverse_acc(Endnumber, Current + 1, [Current | Acc ]).

Roelof




More information about the erlang-questions mailing list