Erlang:使用递归从列表中选择唯一的项目 [英] Erlang: choosing unique items from a list, using recursion

查看:88
本文介绍了Erlang:使用递归从列表中选择唯一的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  L = [foo,bar,foo,buzz,foo]。 

如何使用递归函数仅显示该列表的唯一项?
我不想使用一个内置函数,就像其中一个列表函数(如果存在)。



在我的例子中,我想要要获得一个新的列表,例如

  SL = [bar,buzz]。 

我的猜测是,在应用过滤器之前,先使用快速排序功能排序列表?



任何建议都将有所帮助。这个例子是Cesarini's&汤普森优秀的Erlang编程书。

解决方案

我提出这个:

  unique(L) - > 
unique([],L)。
unique(R,[]) - > R等
unique(R,[H | T]) - >
case member_remove(H,T,[],true)
{false,Nt} - >唯一的(R,Nt个);
{true,Nt} - >唯一([H | R],Nt)
结束。

member_remove(_,[],Res,Bool) - > {BOOL,RES};
member_remove(H,[H | T],Res,_) - > member_remove(H,T,RES,假);
member_remove(H,[V | T],Res,Bool) - > member_remove(H,T,[V |高分辨率],布尔)。

member_remove函数在一次通过中返回剩余的尾部,而不会检查要复制的元素的所有出现,测试结果。


Given any list in Erlang, e.g.:

L = [foo, bar, foo, buzz, foo].

How can I only show the unique items of that list, using a recursive function? I do not want to use an built-in function, like one of the lists functions (if it exists).

In my example, where I want to get to would be a new list, such as

SL = [bar, buzz].

My guess is that I would first sort the list, using a quick sort function, before applying a filter?

Any suggestions would be helpful. The example is a variation of an exercise in chapter 3 of Cesarini's & Thompson's excellent "Erlang Programming" book.

解决方案

I propose this one:

unique(L) ->
    unique([],L).
unique(R,[]) -> R; 
unique(R,[H|T]) ->
    case member_remove(H,T,[],true) of
        {false,Nt} -> unique(R,Nt);
        {true,Nt} -> unique([H|R],Nt)
    end.

member_remove(_,[],Res,Bool) -> {Bool,Res};
member_remove(H,[H|T],Res,_) -> member_remove(H,T,Res,false);
member_remove(H,[V|T],Res,Bool) -> member_remove(H,T,[V|Res],Bool).

The member_remove function returns in one pass the remaining tail without all occurrences of the element being checked for duplicate and the test result.

这篇关于Erlang:使用递归从列表中选择唯一的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆