[Haskell-cafe] Type inference problem with division (/)

Shachaf Ben-Kiki shachaf at gmail.com
Tue Oct 30 21:19:49 EDT 2007

```On 10/30/07, Tim Chevalier <catamorphism at gmail.com> wrote:
> On 10/30/07, noa <noandrews at gmail.com> wrote:
> >
> > Hi!
> >
> > I have the following function:
> >
> > theRemainder :: [String] -> [String] -> Double
> > theRemainder xs xt = sum( map additional (unique xs) )
> >         where
> >         additional x = poccur * (inf [ppos,pneg]) --inf takes [Double]
> >                 where
> >                 xsxt = zip xs xt
> >                 pi = countPos xr -- countPos returns an Int
> >                 ni = (length xr) - pi
> >                 len = length xs
> >                 len2 = length xr
> >                 ppos = pi/len2 -- THESE ARE THE PROBLEM
> >                 pneg = ni/len2 -- THESE ARE THE PROBLEM
> >                 poccur = (pi+ni)/len
> >                 xr = (filter ((\y -> (fst y)==x)) (xsxt))
> >
> > And I am getting this error message with ghc:
> >
> > matrix.hs:54:31:
> >     Couldn't match expected type `Double' against inferred type `Int'
> >     In the expression: ppos
> >     In the first argument of `inf', namely `[ppos, pneg]'
> >     In the second argument of `(*)', namely `(inf [ppos, pneg])'
> >
> > How can I change the declaration of ppos nad pneg so they are treated as
> > Double for the inf function?
> >
>
> ppos = pi/len2; pi and len2 are both Ints, so dividing them gives you
> an Int. To convert to a Double, write ppos = fromIntegral (pi/len2).
> (Type :t fromIntegral in ghci to see what else fromIntegral can be
> used for.)

You can't divide Ints with (/) at all -- they aren't Fractional.
You'll probably want to either fromIntegral both pi and len2 or use
div for integer division.

(Also, pi is a bit of a confusing name; you may want to consider using
another one.)

Shachaf
```