简体   繁体   English

Erlang在列表中查找连续的相同元素

[英]Erlang Find consecutives same element in list

I need to find consecutive same element from a LIST. 我需要从列表中找到连续的相同元素。

start from any position 从任何位置开始

ie [BCCDAB] expected result [cc] [BCDCBA] expected result [] 即[BCCDAB]预期结果[cc] [BCDCBA]预期结果[]

any suggestion? 有什么建议吗? thanks 谢谢

extractcc(L) -> extractcc(L,[]).

etractcc([],R) -> lists:reverse(R);
extractcc([H,H|T],R) -> extactcc(T,[H,H|R]);
extractcc([_H|T],R) -> extractcc(T,R).

this will work for your example, but will have a strange behaviour if there are more than 2 consecutive elements. 这将适用于您的示例,但是如果有两个以上连续的元素,则会有奇怪的行为。 Here an example written in the shell: 这是在shell中编写的示例:

1> Ex = fun Ex([],R) -> lists:reverse(R);
1> Ex([H,H|T],R) -> Ex(T,[H,H|R]);       
1> Ex([_H|T],R) -> Ex(T,R) end.          
#Fun<erl_eval.36.90072148>
2> E = fun(L) -> Ex(L,[]) end.
#Fun<erl_eval.6.90072148>
3> E([1,2,3,3,4,3]).
[3,3]
4> E([1,2,1,2,1]).
[]
5> E([1,2,2,2,3]).
[2,2]
6> E([1,2,2,2,2,3]).
[2,2,2,2]

I let you find how to code the expected behaviour. 我让您找到如何编码预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM