问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/16046586/erlang-basic-recursion-with-guards