How to extract Haskell list items that are in even place

Hello dear Community,

I want to get all the elements that are at an even position in the list. This is for the implementation of the game of darts.

eg. [((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 that, of course, did not work. I would be very happy if someone could offer me a better solution.

Thank! Nazar

+4
source share
3 answers

Two useful features for the price of one:

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

odds (_:xs) = evens xs
odds _ = []
+12
source

We can build a function even_elem :: [a] -> [a]that has, as a database, of course, an empty list:

even_elem [] = []

in addition, if we pass it a list with one element, we will return a list with this element:

even_elem [x] = [x]

, (x1:x2:t), x1 t:

even_elem (x1:_:t) = x1 : even_elem t

:

even_elem :: [a] -> [a]
even_elem [] = []
even_elem [x] = [x]
even_elem (x1:_:t) = x1 : even_elem t

, , [] , :

even_elem :: [a] -> [a]
even_elem (x1:_:t) = x1 : even_elem t
even_elem l = l
+5

You can also use foldrwith ziplike;

evens :: [a] -> [a]    
evens = foldr (\t r -> if fst t `mod` 2 == 0 then snd t : r else r) [] . (zip [0..])
+1
source

Source: https://habr.com/ru/post/1685897/


All Articles