1
\$\begingroup\$

I have just started learning erlang...I am just practicing the recursion and all in erlang...I tried to write a few of the list processing functions on my own in erlang...Can someone review the code and give some advice on it...

-module(listma).
-export([duplicates/1,reverse/1])
%% Remove the duplicates in a list
duplicates(List) ->
 duplicates(List,[]).
duplicates([Head|Tail],Newlist) ->
 Insert = 
 fun(H,N) -> 
 case [H] -- N of
 [] -> N;
 [H] -> [H|N]
 end
 end,
 duplicates(Tail,Insert(Head,Newlist));
duplicates([],Outputlist) ->
 reverse(Outputlist).
%% Reverse a list
reverse(List) ->
 reverse(List,[]).
reverse([Head|Tail],Newlist) ->
 reverse(Tail,[Head|Newlist]);
reverse([],Outputlist) ->
 Outputlist.
asked Apr 10, 2013 at 11:05
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Your Insert lambda doesn't use any context so you could rewrite it as a top-level function or move its body to the clause. And you could use lists:member/2 instead of --.

I'd write first clause like this:

duplicates([Head | Tail], Acc) ->
 NewAcc = case lists:member(Head, Acc) of
 true ->
 Acc;
 _ ->
 [Head | Acc]
 end,
 duplicates(Tail, NewAcc);
answered Apr 10, 2013 at 12:12
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for the feedback Dmitry...Thank you so much...The Insert Lambda is useless here as you said...I will remove it...I wanted to practice lists processing functions without the use of lists Built in functions like member,delete,append,etc..Thats why i ignored lists:member thing and used -- operator....Thanks again Dmitry...Thank you so much \$\endgroup\$ Commented Apr 10, 2013 at 12:30
  • \$\begingroup\$ Well, you can write your own member function too without use of -- =) \$\endgroup\$ Commented Apr 10, 2013 at 12:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.