tags:

views:

45

answers:

1

How does one split a list which is passed as an argument to a function and tag each element with a number?

The problem I have is how to increment in erlang as there are no for loops.

Thanks

+4  A: 

Is this what you're trying to do?

tagger(List) ->
    tagger(List, 0).
tagger([Head|Tail], Index) ->
    [{Head, Index}|tagger(Tail, Index + 1)];
tagger([], _Index) ->
    [].

Because if it is, you can use lists:mapfoldl:

lists:mapfoldl(fun (A, AccIn) -> {{A, AccIn}, AccIn + 1} end, 0, List).
Nathon
Thanks. this is what I was trying to do. But not using BIFs.
alJaree
1st, BIFs are not dangerous, and if this is course work, please ask your supervisor. 2nd the example above is first of all wrong and secondly unnecessarily complicated. An easier (correct) solution is lists:zip(lists:seq(1, length(List)), List).
Daniel Luna
@Daniel Luna: The second example looks good to me. It only traverses the list once, while yours traverses it twice, plus it also builds a throw-away list of numbers.
Zed
Oh, sorry about that. Yes it's correct.
Daniel Luna