0

I'm trying to implement drop function in Erlang:
Returning a collection of all but the first n items in a list.

step(N, C) ->
[_ | T] = C,
case (N > 0) and (length(C) > 0) of
  true ->
    step(N - 1, T);
  false ->
    C
end.


drop(_, [ ]) ->
  [ ];


drop(Number, Collection) ->
   step(Number, Collection).

In Erlang terminal:

 drop(3, [11, 22, 33, 44, 55, 66, 77]).
 "7BM"

Any ideas why I'm getting that output?

Feel free to suggest more idiomatic Erlang approach.

Chiron
  • 20,081
  • 17
  • 81
  • 133
  • [This answer](http://stackoverflow.com/a/10043482/113848) might give a hint, as well as [this question](http://stackoverflow.com/q/2348087/113848) or [this question](http://stackoverflow.com/q/7371955/113848). – legoscia Mar 26 '14 at 15:02

2 Answers2

2

Strings in erlang are lists of integers, and if all those values fall in the ASCII range then the repl displays the list as a string. Note your drop implementation appears to be dropping n + 1 elements from the input list since drop(3, [11, 22, 33, 44, 55, 66, 77]) should be [44, 55, 66, 77].

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Oh, how I can keep the result list as integers? I want to return [44, 55, 66, 77] – Chiron Mar 26 '14 at 15:05
  • I corrected the boolean condition. Thanks for your hint. – Chiron Mar 26 '14 at 15:10
  • @Chiron - The result is still a list of ints, it's just the repl formatting them in this way. If you want to see the underlying values you could do `io:format("~w", drop(3, [11, 22, 33, 44, 55, 66, 77]))` – Lee Mar 26 '14 at 15:16
2
-module(wy).
-compile(export_all).


drop(_, []) ->
     [];
drop(0, Collection) ->
    Collection;
drop(Number, [_H | T]) ->
    drop(Number - 1, T).


main() ->
    L =  [11, 22, 33, 44, 55, 66, 77],
    io:format("~w~n", [drop(3, L)]).

The output is: [44,55,66,77]

w

Writes data with the standard syntax. This is used to output Erlang terms. Atoms are printed within quotes if they contain embedded non-printable characters, and floats are printed accurately as the shortest, correctly rounded string.

p

Writes the data with standard syntax in the same way as ~w, but breaks terms whose printed representation is longer than one line into many lines and indents each line sensibly. It also tries to detect lists of printable characters and to output these as strings. The Unicode translation modifier is used for determining what characters are printable.
BlackMamba
  • 10,054
  • 7
  • 44
  • 67