Skip to content

Instantly share code, notes, and snippets.

@pppillai
Created May 18, 2020 18:06
Show Gist options
  • Save pppillai/4c004672684216f50d91b96430622d3c to your computer and use it in GitHub Desktop.
Save pppillai/4c004672684216f50d91b96430622d3c to your computer and use it in GitHub Desktop.
-module(week227).
-compile([export_all]).
-include_lib("eunit/include/eunit.hrl").
join(Xs, Ys) ->
accumulate(shunt(Xs, []), Ys).
shunt([], Ys) ->
Ys;
shunt([X|Xs], Ys) ->
shunt(Xs, [X|Ys]).
accumulate([] ,Result) ->
Result;
accumulate([X|Xs], Result) ->
accumulate(Xs, [X|Result]).
concat([]) ->
[];
concat([X|Xs]) ->
join(X,concat(Xs)).
member(_N, []) ->
false;
member(N, [X|Xs]) ->
case X =:= N of
true ->
true;
false ->
member(N, Xs)
end.
perms([]) ->
[[]];
perms(L) ->
[[X|Y] || X <- L, Y <- perms(L--[X])].
tests() ->
?assertEqual(join([],[]),[]),
?assertEqual(join([1,2,3],[4,5,6]),[1,2,3,4,5,6]),
?assertEqual(concat(["hello", "world"]),"helloworld"),
% ?assertEqual(concat([]), []),
?assertEqual(perms([]), [[]]),
?assertEqual(perms([1,2,3]), [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]).
@elbrujohalcon
Copy link

A few things to notice…

  1. for ?assertEqual/2… the expected result is the first argument. You will notice that in the output when the assertion fails.
  2. You can use pattern-matching more aggressively on member/2
member(_N, []) -> false;
member(N, [N|_]) -> true;
member(N, [_|Xs]) -> member(N, Xs).

2.5. Or you can use short-circuiting…

member(_, []) -> false;
member(N, [X|Xs]) -> N =:= X orelse member(N, Xs).
  1. Do you understand how perms/1 works? I'll leave this here, just in case :trollface:

@pppillai
Copy link
Author

Thanks will go thorough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment