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!
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]).
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]).
In Erlang, Lists are created by enclosing the values in square brackets.
[X1, X2 | Tail] = List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With