Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove even indexes in Haskell?

Newbie to functional program, I need to remove even indexed elements from a list, so far i can only create a list, from 1 to n.
The list : [1,2,3,4,5,6…100]
Goal: [1,3,5,7,9…99]

main = do
    input <- readLn :: IO Int
    let a = input 
    let list=[1..a] 
    putStrLn $ show list

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can produce a list that only contains the odd elements by making use of a range that starts with 1 then 3 and as limit a:

main = do
    input <- readLn :: IO Int
    print [1, 3..a]

This will make a call to enumFromThenTo :: Enum a => a -> a -> a -> [a] that will thus generate a list with steps of two.

You can also make two functions with mutual recursion:

evens :: [a] -> [a]
evens [] = []
evens (_:xs) = odds xs

odds :: [a] -> [a]
odds [] = []
odds (x:xs) = x : evens xs

Then calling odds on a list [1 .. 100] produces:

Prelude> odds [1 .. 100]
[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99]

and evens can be used to obtain the elements on even indices.

Elaborating slightly on what this mutual recursion looks like with a simple example list:

odds [1, 2, 3, 4, 5, 6]
1 : evens [2, 3, 4, 5, 6]
1 : odds [3, 4, 5, 6]
1 : 3 : evens [4, 5, 6]
1 : 3 : odds [5, 6]
1 : 3 : 5 : evens [6]
1 : 3 : 5 : odds []
1 : 3 : 5 : []
[1, 3, 5]

or if you want to remove items that are even (not even indices), you can work with:

Prelude> filter odd [1, 4 .. 100]
[1,7,13,19,25,31,37,43,49,55,61,67,73,79,85,91,97]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading