AnchovyLegend
AnchovyLegend

Reputation: 12538

Erlang basic recursion with guards

I am trying to create a very simple recursive function to delete all element that have a particular value that the user decides on from a list.

In haskell I would use guards and do:

deleteAll_rec _ [] = []
deleteAll_rec del (x:xs) | del==x = deleteAll_rec del xs
                         | otherwise = x:deleteAll_rec del xs

I am trying to code up an Erlang equivalent, however, I am not sure how to handle the otherwise case:

deleteAll_rec(_, []) -> [];
deleteAll_rec(DEL, [X|XS]) when DEL =:= X -> deleteAll_rec(DEL, XS).

I was wondering if someone can demonstrate how this can be done?

Many thanks in advance!

Upvotes: 0

Views: 194

Answers (1)

rvirding
rvirding

Reputation: 20916

The otherwise becomes a separate clause in Erlang:

delete_all_rec(_, []) -> [];
delete_all_rec(Del, [Del|Xs]) ->
    delete_all_rec(Del, Xs);
delete_all_rec(Del, [X|Xs]) ->
    [X|delete_all_rec(Del, Xs)].

An alternative is to use an if like:

delete_all_rec(_, []) -> [];
delete_all_rec(Del, [X|Xs]) ->
    if Del =:= X ->
            delete_all_rec(Del, Xs);
        true ->
            [X|delete_all_rec(Del, Xs)]
    end.

The resultant code is the same but I think the first version looks better. Whether you put the terminating case first or last is irrelevant in this example, I prefer putting it last.

Upvotes: 5

Related Questions