views:

97

answers:

1

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!

+13  A: 
[X1, X2 | Tail] = List.
rkhayrov
Thanks, not sure why I didn't think of that!
Jeff Zellner