How can I access a list by index in Haskell, analog to this C code?
int a[] = { 34, 45, 56 }; return a[1];
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.
As we want second to last element in list, use -2 as index.
Look here, the operator used is !!
.
I.e. [1,2,3]!!1
gives you 2
, since lists are 0-indexed.
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.
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