[Haskell-cafe] Array functions?

Daniel Carrera dcarrera at digitaldistribution.com
Tue May 3 19:26:18 EDT 2005


Hello,

I hope these don't turn out to be RTFM questions, but I can't find them 
in my FM :-)

1) Is there a function to get the ith element from an array?
2) Is there a function to get the "index" of an entry in an array?

I've implemented these two functions below:

1)
find 0 (x:xs) = x
find n (x:xs) = find (n-1) xs

2)
index i (x:xs) =
    if i == x
      then 0
      else 1 + index a xs


This was a fun exercise, but I can't shack off the feeling that I just 
re-invented the wheel.

I need these because I want to be able to swap any two elements from an 
array. This is my swap function:

-- swap i j array   =>  swaps the ith and jth elements of 'array'.
-- 
swap i j arr = a_head ++ [item_j] ++ a_midd ++ [item_i] ++ a_tail
    where a_head = [a | a <- arr, index a arr  < i]
          item_i = find i arr
          a_midd = [a | a <- arr,(index a arr  > i) && (index a arr < j)]
          item_j = find j arr
          a_tail = [a | a <- arr, index a arr  > j]


I'm sure this was a poor way to accomplish this, but it was a learning 
experience. If anyone would like to show me a more elegant solution, I 
would be happy to see it.

Cheers,
Daniel.
Haskell newbie.


More information about the Haskell-Cafe mailing list