Program to filter odd numbers in a number list

Asked

Viewed 503 times

4

I wrote a script in Haskell to find filter the odd numbers from a list and show them on the screen, but I keep getting an error when displaying the results..

impares[] =[]
impares(x:xs) 
        |(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’s nothing wrong with my code, but I can’t run this program! Someone can shed some light?

1 answer

4


The error is in the way you use the operator mod. Set your function to

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

Or if you want to use 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
  • 1

    Gratitude! now I’ve connected as eh!

  • impares = filter odd is very elegant. Good suggestion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.