views:

243

answers:

2

This is simple code designed to take a decimal number and return a string representing the equivalent in binary.

b2d :: Int -> String

b2d 1 = "1"
b2d x = show (x `mod` 2) ++ b2d  x/2

However, when I try to run this through hugs, it gives me an error:

:3 - Instance of fractional [Char] required for definition of b2d

I don't know what this means. Can anyone tell me how to fix it?

Cheers.

+9  A: 

you probably wanted (function calls have higher precedence than operators):

b2d (x/2)

also your first case should probably not take 2 arguments

newacct
+6  A: 

/ is the fractional division operator. For integers, you need to use div (and add parentheses as newacct mentioned):

b2d x = show (x `mod` 2) ++ b2d (x `div` 2)

For extra efficiency points, use divMod to only perform one division:

b2d x = let (q,r) = x `divMod` 2
        in show r ++ b2d q
Nefrubyr