Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repair an improper list in Erlang?

Tags:

erlang

I accidentally did (the equivalent of) the following:

lists:foldl(fun(X, Acc) -> [X|Acc] end, 0, List).

Note the not-a-list initial value for the accumulator.

This resulted in an improper list. This means that length, etc., don't work on it.

Given that my "equivalent of" took an hour to run, and I don't want to run it again, how do I repair my improper list?

For a simpler example of an improper list and the problem that it causes:

1> L = [1|[2|[3|4]]].
[1,2,3|4]
2> length(L).
** exception error: bad argument
     in function  length/1
        called as length([1,2,3|4])
like image 272
Roger Lipscombe Avatar asked Nov 30 '25 18:11

Roger Lipscombe


1 Answers

If you want to preserve the "improper tail", this would be enough:

Fix = fun Fix([H | T]) -> [H | Fix(T)];
          Fix(T) -> [T]
      end.
like image 113
Dániel Szoboszlay Avatar answered Dec 07 '25 16:12

Dániel Szoboszlay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!