[Haskell-cafe] Array functions?

Benjamin Franksen benjamin.franksen at bessy.de
Tue May 3 19:48:17 EDT 2005

On Wednesday 04 May 2005 01:26, Daniel Carrera wrote:
> Hello,
> I hope these don't turn out to be RTFM questions, but I can't find them
> in my FM :-)

Take a look at this one:


> 1) Is there a function to get the ith element from an array?

From your own implementations I gather you mean 'list', not 'array'.

In the above document search for 'index'. You find:

-- List index (subscript) operator, 0-origin
 (!!)                :: [a] -> Int -> a
 xs     !! n | n < 0 =  error "Prelude.!!: negative index"
 []     !! _         =  error "Prelude.!!: index too large"
 (x:_)  !! 0         =  x
 (_:xs) !! n         =  xs !! (n-1)
> 2) Is there a function to get the "index" of an entry in an array?

This one is not so obvious. It is not in the Prelude but in teh H98 standard 
library, see http://www.haskell.org/onlinelibrary/list.html. You'll find

 elemIndex           :: Eq a => a -> [a] -> Maybe Int
 elemIndices         :: Eq a => a -> [a] -> [Int]
 find                :: (a -> Bool) -> [a] -> Maybe a
 findIndex           :: (a -> Bool) -> [a] -> Maybe Int
 findIndices         :: (a -> Bool) -> [a] -> [Int]


17.1  Indexing lists
elemIndex val list returns the index of the first occurrence, if any, of val 
in list as Just index. Nothing is returned if not (val `elem` list).
elemIndices val list returns an in-order list of indices, giving the 
occurrences of val in list.
find returns the first element of a list that satisfies a predicate, or 
Nothing, if there is no such element. findIndex returns the corresponding 
index. findIndices returns a list of all such indices.

Now, if you happen to also want to know these functions for real arrays, not 
lists, I suppose you take a look at the standard library module Array.


More information about the Haskell-Cafe mailing list