How can I get nth element from a list?

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

    Haskell's standard list data type forall t. [t] in implementation closely resembles a canonical C linked list, and shares its essentially properties. Linked lists are very different from arrays. Most notably, access by index is a O(n) linear-, instead of a O(1) constant-time operation.

    If you require frequent random access, consider the Data.Array standard.

    !! is an unsafe partially defined function, provoking a crash for out-of-range indices. Be aware that the standard library contains some such partial functions (head, last, etc.). For safety, use an option type Maybe, or the Safe module.

    Example of a reasonably efficient, robust total (for indices ≥ 0) indexing function:

    data Maybe a = Nothing | Just a
    
    lookup :: Int -> [a] -> Maybe a
    lookup _ []       = Nothing
    lookup 0 (x : _)  = Just x
    lookup i (_ : xs) = lookup (i - 1) xs
    

    Working with linked lists, often ordinals are convenient:

    nth :: Int -> [a] -> Maybe a
    nth _ []       = Nothing
    nth 1 (x : _)  = Just x
    nth n (_ : xs) = nth (n - 1) xs
    
    0 讨论(0)
提交回复
热议问题