Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to split several heads from a list with Erlang?

So, Erlang is a real joy to work with, but there's one problem I run into occasionally, that I'm wondering if there is a nicer way to solve. Often, I find myself needing to split several items from a list. The syntax for splitting a list into a Head and Tail is straight forward enough, but what about when there are multiple items.

1> List = [1,2,3,4,5].
[1,2,3,4,5]
2> [Head | Tail] = List.
[1,2,3,4,5]
3> Head.
1
4> Tail.
[2,3,4,5]

Is there a nicer way to get, say, the first two elements of a list other than splitting twice inline?

1> List = [1,2,3,4,5].
[1,2,3,4,5]
2> [Head1 | [Head2 | Tail]] = List.
[1,2,3,4,5]
3> Head1.
1
4> Head2.
2
5> Tail.
[3,4,5]

I know that this can also be simplified by writing functions that recursively split subsequent heads from a list, but I'm wondering if there is a simpler inline way to do it (or if in fact, the recursive subsequent split functions are the best practices way to accomplish this task)? Thanks!

like image 361
SEVEN YEAR LIBERAL ARTS DEGREE Avatar asked Jul 23 '10 18:07

SEVEN YEAR LIBERAL ARTS DEGREE


People also ask

How do I split a list in Erlang?

You can use lists:split/2 for this: divide(L, N) -> divide(L, N, []). divide([], _, Acc) -> lists:reverse(Acc); divide(L, N, Acc) when length(L) < N -> lists:reverse([L|Acc]); divide(L, N, Acc) -> {H,T} = lists:split(N, L), divide(T, N, [H|Acc]).

How do I find the length of a list in Erlang?

You can use length() to find the length of a list, and can use list comprehensions to filter your list. num(L) -> length([X || X <- L, X < 1]).

How do I create a list in Erlang?

In Erlang, Lists are created by enclosing the values in square brackets.


1 Answers

[X1, X2 | Tail] = List.
like image 139
rkhayrov Avatar answered Sep 17 '22 13:09

rkhayrov