Recursiveness-elemindices

Asked

Viewed 94 times

2

They know how to recursively define the elemindices function, predefined in Prelude. I defined it in a way, but it doesn’t give the expected result.

myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices x (h:t) | x == h = 0 : myElemIndices x t
                      | otherwise = myElemIndices x t
  • What is the expected result?

  • elemIndices 3 [1,2,3,4,3,2,3,4,5] corresponds to [2,4,6].

1 answer

0


I’ll explain two ways that work but I don’t know if it’s really what you want:

myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices a xs = indexed a (zip xs [0..])
    where indexed _ [] = [] 
          indexed a ((x,i):xs) 
              | x == a = i:indexed a xs
              | otherwise = indexed a xs

I’m using an internal function called Indexed that assigns indexes to the list using the zip function. This function returns tuples with the union of the lists, in this case it is (X1, 1), (x2, 2) ... (Xn , n). With each recursive round where the equality x== a is true I make the index append on the result. (See repl it. - credit to the author: Counting positions in a list Haskell)

Or you can use a different auxiliary function:

myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices x xs = count 0 x xs

count :: Eq a => Int -> a -> [a] -> [Int]
count c x [] = []
count c x (y:ys)
   | x == y = c:count (c+1) x ys
   | otherwise = count (c+1) x ys

In the above case I use a function with an extra argument to count. When x = y he gives an append on the current counter and passes on with counter + 1. (See working on repl it.)

  • Thank you very much, that’s what I intended :)

  • Could you mark the answer as accepted? There is a green OK under the arrows | v

Browser other questions tagged

You are not signed in. Login or sign up in order to post.