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.
Use
div, which performs integer division:The
(/)function requires arguments whose type is in the class Fractional, and performs standard division. Thedivfunction requires arguments whose type is in the class Integral, and performs integer division.More precisely,
divandmodround toward negative infinity. Their cousins,quotandrem, behave like integer division in C and round toward zero.divandmodare usually correct when doing modular arithmetic (e.g. when calculating the day of the week given a date), whilequotandremare slightly faster (I think).Playing around a bit in GHCi: