Erlang List concatenation, weird “|” sign

[亡魂溺海] 提交于 2020-01-04 01:57:07

问题


in order to become familar with Erlang, i'm trying to write my own Bubblesort Algorithm. Right now, i have the following code in my module:

-module(mysort).
-export([bubblesort/1]).

bubblesort(L) ->
    sort_sequence(L, []).

sort_sequence([H1|[H2|T]], Sorted) ->
    if H2 >= H1 ->
        sort_sequence(T, Sorted ++ [H1, H2]);
    H2 < H1 ->
        sort_sequence(T, Sorted ++ [H2, H1])
    end;
sort_sequence([H|T], Sorted) ->
    Sorted ++ H;
sort_sequence([], Sorted) ->
    Sorted.

first of all: please don't give me suggestions to my code i want to figure it out myself ^^

the problem is: if i say mysort:bubblesort([2,1,3,4,5]). the output is as i would expect: [1,2,3,4,5]

but if i say mysort:bubblesort([2,1,3,5,4]). the output is: [1,2,3,5|4].

my only question is: what does this "|" sign mean in between the listitems ?!

thank you all!


回答1:


A list can have two forms: Either it is empty ([]), or it has a head and a tail ([H|T]). So [] is an empty list, [1 | []] is a list whose head is 1 and whose tail is [], and [1|2] is a list whose head is 1 and whose tail is 2.

A list is called a proper list if it is empty or its tail is a proper list. So [] is a proper list because its empty and [1|[]] is a proper list because its tail is the empty list (which is a proper list), but [1|2] is not a proper list because its tail is 2 and 2 is not a proper list.

Since proper lists are the most common types of lists and reading and writing them as nested lists like that is kind of cumbersome, there's a special syntax for them: A proper list is displayed and can be written by separating the heads of the sublists with commas. So if we have the proper list [1 | [2 | [3 | []]]] it is displayed as [1,2,3] (and we can also write it that way), which is much more readable.

This format is also used to display the beginning of improper lists if they "start out" proper up to the point where the non-proper tail is, which will be separated with a |. So for example if we have the improper list [1 | [2 | [3|4]]] (which is improper because the innermost tail is 4, which is not a proper list), it will be displayed as [1,2,3|4] to distinguish it from the proper list [1 | [2 | [ 3 | [4 | []]]]], which would be displayed as [1,2,3,4].

So if you see something like that, you somehow created a list whose tail is not a proper list.




回答2:


This occurs when tail not list:

> [1,2,3 | 2].
[1,2,3|2]

> [1,2,3 | [2]].
[1,2,3,2]



回答3:


first: thank you guys !

sort_sequence([H|T], Sorted) ->
    Sorted ++ H;

i concated a single item to the list which is of course not a proper list; which resulted into the error you both explained



来源:https://stackoverflow.com/questions/10969447/erlang-list-concatenation-weird-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!