Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get nth element from a list?

Tags:

haskell

How can I access a list by index in Haskell, analog to this C code?

int a[] = { 34, 45, 56 }; return a[1]; 
like image 358
eonil Avatar asked Mar 07 '11 07:03

eonil


People also ask

How do you print every nth element from an array?

To get every Nth element of an array:Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array. The final array will contain every Nth element of the original array.

How do you select the second item in a list Python?

As we want second to last element in list, use -2 as index.


2 Answers

Look here, the operator used is !!.

I.e. [1,2,3]!!1 gives you 2, since lists are 0-indexed.

like image 159
phimuemue Avatar answered Sep 21 '22 10:09

phimuemue


I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!, in your case you might search for "something that takes an Int and a list of whatevers and returns a single such whatever", namely

Int -> [a] -> a 

Lo and behold, with !! as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?

Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.

like image 42
gspr Avatar answered Sep 18 '22 10:09

gspr