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.)
What is the expected result?
– Gustavo Fragoso
elemIndices 3 [1,2,3,4,3,2,3,4,5] corresponds to [2,4,6].
– João Sampaio