Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Type Signature Error

My function does not work. I tried many different Type signatures. If I remove the Type Signature it does not work with a point number as "p".

fak :: (Num a, Ord a) => a->a
fak x
    | x <= 1 = 1
    | otherwise = x*fak (x-1)

ncr :: Integral a => a -> a -> a
ncr n k = (fak n) `div` (fak(n-k) * fak k)

bTable :: (Integral a, Num b) => a->b->a->a 
bTable n p k = (ncr n k) * p^k * (1-p)^(n-k)

Inferred type is not general enough

*** Expression    : bTable
*** Expected type : (Integral a, Num b) => a -> b -> a -> a
*** Inferred type : (Integral a, Num a) => a -> a -> a -> a

If I remove the Type Signature I get:

:t bTable
bTable :: Integral a => a -> a -> a -> a

But If I enter:

bTable 50 0.8 10

I get

Unresolved overloading
*** Type       : (Fractional a, Integral a) => a
*** Expression : bTable 50 0.8 10
like image 835
A. Ano Avatar asked Dec 20 '25 22:12

A. Ano


1 Answers

Use fromIntegral to convert the return value of ncr to something you can multiply with Num a => a values.

bTable n p k = fromIntegral (ncr n k) * p^k * (1-p)^(n-k)

Note the inferred type of this function is then

bTable :: (Num a, Integral b) => b -> a -> b -> a

which is slightly different from your attempted declared type (with constraints renamed for comparison to the type above)

bTable :: (Num a, Integral b) => b -> a -> b -> b 
like image 114
chepner Avatar answered Dec 22 '25 14:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!