Home > Software design >  How to remove even indexes in Haskell?
How to remove even indexes in Haskell?

Time:12-17

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

CodePudding user response:

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, 4, 2, 7, 9, 6]
1 : evens [4, 2, 7, 9, 6]
1 : odds [4, 7, 9, 6]
1 : 2 : evens [7, 9, 6]
1 : 2 : odds [9, 6]
1 : 2 : 9 : evens [6]
1 : 2 : 9 : odds []
1 : 2 : 9 : []
[1, 2, 9]

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]
  • Related