Recursion- elemindices

2

They know how to recursively define the elemindices function, pre-defined in Prelude. I defined it in a way, but it does not 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
    
asked by anonymous 17.10.2017 / 22:16

1 answer

0

I'll explain two ways that work but I do not 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 lists, in case it gets (x1, 1), (x2, 2) ... (xn, n). At each recursive round in which the equality x == a is true I make the index append in the result. (See repl.it - author credits: Counting positions in a haskell list )

Or you can use a different helper 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 case above I use a function with one more argument to count. When x = y it gives an append on the current counter and passes on with counter + 1. (See working at repl.it ) / p>     

18.10.2017 / 16:02