How can I get nth element from a list?

前端 未结 7 683
长发绾君心
长发绾君心 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:21

    The straight answer was already given: Use !!.

    However newbies often tend to overuse this operator, which is expensive in Haskell (because you work on single linked lists, not on arrays). There are several useful techniques to avoid this, the easiest one is using zip. If you write zip ["foo","bar","baz"] [0..], you get a new list with the indices "attached" to each element in a pair: [("foo",0),("bar",1),("baz",2)], which is often exactly what you need.

提交回复
热议问题