How can I get nth element from a list?

前端 未结 7 655
长发绾君心
长发绾君心 2020-12-12 18:51

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

int a[] = { 34, 45, 56 };
return a[1];
7条回答
  •  有刺的猬
    2020-12-12 19:25

    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.

提交回复
热议问题