woj_jas
woj_jas

Reputation: 1088

How to sum elements in haskell (odd and divided by 3)

I'm trying to write function in haskell , I want that function to sum only odd and divided by 3 elements from list.

my code is :

nieplist n = (n/2 > 1) && mod n 3 == 0
niepdodlist xs = sum $ filter nieplist xs

I think that everything should work , first i'm checking if number from list is odd after that i want to check if it's divided by 3. (number module 3 always will be 0 )

When i try to write:

*Main>niepdodlist [1,2,3,6]

result is

<interactive>:220:1:
No instance for (Integral a0) arising from a use of `niepdodlist'...


<interactive>:220:14:
No instance for (Num a0) arising from the literal `1'
The type variable `a0' is ambiguous...

The Result Should be:

*Main>niepdodlist [3,6,3]
>9 

Solution (thanks to @kqr)

nieplist n = odd n && mod n 3 == 0
niepdodlist xs = sum $ filter nieplist xs

Upvotes: 0

Views: 1656

Answers (2)

Mephy
Mephy

Reputation: 2986

For the error, the function (/) is defined as (/) :: Fractional a => a -> a -> a, but the function mod as mod :: Integral a => a -> a -> a. As you can see, one uses fractionals and the other uses integrals. One solution would be using div or quot (you can infix using backticks).

5 `div` 2 = 2

For the logic, to test if a number is odd you should only test n % 2 == 0, (n/2 > 1) does not accomplish the same result (any number greater than 3 will do it!).

This function is also a good example for list comprehensions.

niepdodlist xs = sum [x | x <- xs, odd x, x mod 3 == 0]

Upvotes: 1

kqr
kqr

Reputation: 15028

If you are looking for odd integers, this: (n/2 > 1) is probably wrong. You might want to try replacing it with odd n. It just happens that odd is a function in the standard library!

The reason you get such a scary-looking error is because the division operator (/) can only be used with fractional numbers, but the modulo function (mod) can only be used with integral numbers. So the type checker gets confused about whether you want n to be an integer or a float.

But keep in mind that based on your description of the problem, the result of

niepdodlist [3,6,3]

should be 6, not 12! Since 6 is an even number it doesn't count towards the sum.

Upvotes: 3

Related Questions