Build a program which chooses evenly indexed items in a list

123 views Asked by At

I have been trying to learn list comprehensions. I am trying to code a program in Haskell which returns only the evenly indexed values in a list of any type. I am struggling to find how to find the even indexes in Haskell. I then want to create an odds function that returns the remaining elements using the evens function I am making. This is what I have so far:

 evens :: [a] -> [a]
 evens (x:xs) = [x | x <- xs, xs !! 2n]

I need to fix the condition for this as I do not know what to add after the ',' and how to implement the odd function.

1

There are 1 answers

0
willeM_ Van Onsem On

You can recurse on the rest of the list through pattern matching:

evens :: [a] -> [a]
evens (x:_:xs) = …  -- (1)
evens [x] = …
evens [] = …

Here for the first line (1), the pattern (x:_:xs) will assign the first item to x and xs will bind with the list of remaining items after the first two items.

I leave the parts as an exercise.