1

I wrote the function:

rotate_bin_list_right([H|T]) ->
  erlang:display(H),
  erlang:display(T),
  erlang:display([T|H]),
  [T|H].

When called with [<<"2">>,<<"3">>,<<"4">>,<<"2">>,<<"3">>,<<"4">>], it prints:

 <<"2">>
[<<"3">>,<<"4">>,<<"2">>,<<"3">>,<<"4">>]
[[<<"3">>,<<"4">>,<<"2">>,<<"3">>,<<"4">>]|<<"2">>]

I was expecting a "flattened list":

[<<"3">>,<<"4">>,<<"2">>,<<"3">>,<<"4">>,<<"2">>]

What is happening?

Tommy
  • 12,588
  • 14
  • 59
  • 110
  • further to what Steve has mentioned in his answer, to get a flattened list as teh return, you must make the 'H' a list, and use the flatten function, like so: `erlang:display(lists:flatten([T|[H]])).` – liam_g Feb 10 '16 at 17:56
  • @liam_g: It's unnecessarily slow implementation. `lists:flatten/1` is Erlang implemented `++/2` is Bif. – Hynek -Pichi- Vychodil Feb 10 '16 at 19:32

2 Answers2

3

T is a list and H is not a list, so the construct [T|H] creates an improper list, where the tail is not a list.

Community
  • 1
  • 1
Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
  • No, @Tommy, `[[H]|T]` gives you a list with a single-element list containing `H` as the head and `T` as the tail. – Steve Vinoski Feb 10 '16 at 19:31
  • 3
    @Tommy, see @Hynek-Pichi-Vychodil's answer for the correct solution. Your fears of `++` are unfounded, as he explains. Also note that my answer doesn't include a solution because that's not what you asked; you merely asked "what's happening". – Steve Vinoski Feb 10 '16 at 19:42
1

Just for sake of completeness, this is correct implementation:

rotate_bin_list_right([H|T]) -> T ++ [H].
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
  • I am new to Erlang, and from what I have read, `++` is very bad as opposed to prepending and reversing because it can lead to quadratic recursive functions. – Tommy Feb 10 '16 at 19:23
  • 2
    @Tommy: I see. You are new to Erlang. So take advice from someone who is not. It is the correct implementation of `rotate_list_right/1` if you like this operation. This is not recursive function so it can't lead to any recursive function including quadratic ones. – Hynek -Pichi- Vychodil Feb 10 '16 at 19:29
  • Thanks for your help. So is there a way to do this in O(1)? – Tommy Feb 11 '16 at 01:27
  • @Tommy: No, there is not a way to do it in O(1) but O(N) is good when you consider it is the immutable single-linked list. – Hynek -Pichi- Vychodil Feb 11 '16 at 17:28