Program to filter odd numbers in a list of numbers

Posted on

Question :

I wrote a haskell script to find the odd numbers in a list and show them on the screen, but I get an error when it comes to displaying the results.

impares[] =[]
        |(mod(x 2)==0) = impares xs
        |otherwise = x:(impares xs)

The error is as follows:

no instance for (show (a10 -> a0)) arising from a use of 'print'

Apparently there is nothing wrong with my code, but I can not execute this program! Can someone give a light?


Answer :

The error is in the way you use the mod operator. Change the definition of your function to

impares [] = []
impares (x:xs) 
        | x 'mod' 2 == 0 = impares xs
        | otherwise      = x:(impares xs)

Or if you want to use the prefix notation you can write like this:

impares [] = []
impares (x:xs) 
        | mod x 2 == 0 = impares xs
        | otherwise    = x:(impares xs)

This function could still be defined using only functions of the Prelude module. An alternative would be:

impares = filter odd


Leave a Reply

Your email address will not be published. Required fields are marked *