I'm making a function in Haskell that halves only the evens in a list and I am experiencing a problem. When I run the complier it complains that you can't perform division of an int and that I need a fractional int type declaration. I have tried changing the type declaration to float, but that just generated another error. I have included the function's code below and was hoping for any form of help.
halfEvens :: [Int] -> [Int] halfEvens [] = [] halfEvens (x:xs) | odd x = halfEvens xs | otherwise = x/2:halfEvens xs
Thank you for reading.
The (/) function requires arguments whose type is in the class Fractional, and performs standard division. The div function requires arguments whose type is in the class Integral, and performs integer division. More precisely, div and mod round toward negative infinity.
The workhorse for converting from integral types is fromIntegral , which will convert from any Integral type into any Num eric type (which includes Int , Integer , Rational , and Double ): fromIntegral :: (Num b, Integral a) => a -> b.
Haskell provides two functions for integer division, div and quot, and two functions for modulus, mod and rem. quot rounds towards 0, and div rounds towards negative infinity. rem is quot's modulus, and mod is div's modulus. mod is Python's %, rem is C's %.
Elem Function This function is used to check whether the supplied list contains a specific element or not. Accordingly, it either returns a true or a false. The following code checks whether the supplied list of elements contains the value 786.
Use div
, which performs integer division:
halfEvens :: [Int] -> [Int] halfEvens [] = [] halfEvens (x:xs) | odd x = halfEvens xs | otherwise = x `div` 2 : halfEvens xs
The (/)
function requires arguments whose type is in the class Fractional, and performs standard division. The div
function requires arguments whose type is in the class Integral, and performs integer division.
More precisely, div
and mod
round toward negative infinity. Their cousins, quot
and rem
, behave like integer division in C and round toward zero. div
and mod
are usually correct when doing modular arithmetic (e.g. when calculating the day of the week given a date), while quot
and rem
are slightly faster (I think).
Playing around a bit in GHCi:
> :t div div :: Integral a => a -> a -> a > :t (/) (/) :: Fractional a => a -> a -> a > 3 / 5 0.6 > 3 `div` 5 0 > (-3) `div` 5 -1 > (-3) `quot` 5 0 > [x `mod` 3 | x <- [-10..10]] [2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1] > [x `rem` 3 | x <- [-10..10]] [-1,0,-2,-1,0,-2,-1,0,-2,-1,0,1,2,0,1,2,0,1,2,0,1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With