Erlang basic recursion with guards

﹥>﹥吖頭↗ 提交于 2021-02-11 17:46:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!