Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erlang: How to get an element form a list by its positional index?

Tags:

python

erlang

In python if I want to retrieve the second element of a list, I can do it like this:

>>> A = [1, 2, 3]
>>> A[1]
2

What is the equivalent of it in erlang?

like image 819
Anthony Kong Avatar asked Mar 12 '14 06:03

Anthony Kong


People also ask

How do I reverse a list in Erlang?

So either use lists:append/1 after your examples:reverse/1 function, or replace reverse([H | T]) -> [reverse(T) | [H]]; with reverse([H | T]) -> reverse(T) ++ [H]; .

Which method is used to get the position of an item in the list?

Index() method is required to get the position of an item in the list.

What are the two types of lists available in Erlang?

You can't seriously program in a language just with scalar types like numbers, strings and atoms. For this reason, now that we have a basic knowledge of Erlang's syntax and variables, we have to delve into two basic vector types: tuples and lists.

How do I create a list in Erlang?

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


1 Answers

We can use the nth method in the lists module.

1> A = [1, 2, 3].
[1,2,3]
2> lists:nth(2, A).
2

Note: The index is not zero based.

like image 170
Anthony Kong Avatar answered Oct 04 '22 01:10

Anthony Kong