Search code examples
listerlangheadtail

Returning a first element from an improper list in Erlang


So I've been trying to implement this function in my module and so far I got this:

EXAMPLE 1.

[2,[3,[4,[5,[6,[7,[8,[]]]]]]]]

I am trying to figure out how I can make it look like a proper list, ie:

EXAMPLE 2.

[2,3,4,5,6,7,8].

I know I have to play with Heads and Tails but I am miserably failing at understanding it. Any help would be appreciated.

Thanks!


Solution

  • Actually in the example 1 you show proper list. List that just consists of 2 elements - number and another list.

    Improper list is different thing - for instance [1|2].

    You can turn example 1 into example 2 by lists:flatten.

    1> M = [2,[3,[4,[5,[6,[7,[8,[]]]]]]]].
    [2,[3,[4,[5,[6,[7,[8,[]]]]]]]]
    2> lists:flatten(M).
    [2,3,4,5,6,7,8]