How can I get nth element from a list?

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

    You can use !!, but if you want to do it recursively then below is one way to do it:

    dataAt :: Int -> [a] -> a
    dataAt _ [] = error "Empty List!"
    dataAt y (x:xs)  | y <= 0 = x
                     | otherwise = dataAt (y-1) xs
    

提交回复
热议问题