Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in Haskell

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.

like image 818
D347th Avatar asked Sep 10 '11 00:09

D347th


People also ask

How do you do division in Haskell?

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.

What does fromIntegral do in Haskell?

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.

What Is REM in Haskell?

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 %.

What does Elem do in Haskell?

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.


1 Answers

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] 
like image 169
Joey Adams Avatar answered Sep 30 '22 18:09

Joey Adams