Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the elements of a Haskell list which are on the even position

Tags:

list

haskell

Hello dear Community,

I want to get all elements which are on a even position in a list. It's for the implementation of a Dart game.

e.g. [((3,20),(1,19),(2,17)),((3,20),(2,12),(2,19))] -> [((3,20),(1,19),(2,17))]

So far i have tried:

positioneven n [] = []
positioneven n (x:xs) = if even n
                          then (x: positioneven n+1 xs)
                          else     positioneven n+1 xs

But this of course didn't work. I would be very glad if someone can suggest me a better solution.

Thank you ! Nazar

like image 508
Mostafa_M Avatar asked Dec 01 '22 11:12

Mostafa_M


1 Answers

Two useful functions for the price of one:

evens (x:xs) = x:odds xs
evens _ = []

odds (_:xs) = evens xs
odds _ = []
like image 134
n. 1.8e9-where's-my-share m. Avatar answered Dec 05 '22 04:12

n. 1.8e9-where's-my-share m.