1
votes

Working on a method to convert a number n into any base b and having some trouble.

Code:

int2Base :: Int -> Int -> String
int2Base n b
    |n == 0 = "0"
    |otherwise = (mod n b) ++ int2Base (div n b) b

and my error:

Couldn't match expected type ‘[Char]’ with actual type ‘Int’
In the second argument of ‘mod’, namely ‘b’
In the first argument of ‘(++)’, namely ‘(mod n b)’

It seems like a simply error but even when I cast it to a char it still expects '[Char]' not [Char]

2
Indeed you cannot concatenate an Int to a String. You will need to convert it to a Char, and then prepend it (with (:)). Once you've done that, you'll discover you're building your result backwards!amalloy
How should I convert it to char? I've tried fromEnum but that doesn't seem to workalex Brock
When you say "any base", do you really mean b <= 10?chepner

2 Answers

3
votes

The problem is here:

(mod n b) ++ int2Base (div n b) b

"(mod n b)" produces an Int, not a String.

This should fix it:

int2Base :: Int -> Int -> String
int2Base n b
    |n == 0 = "0"
    |otherwise = show(mod n b) ++ int2Base (div n b) b
1
votes

if you look at ++ in GHCI

Prelude> :t (++)
(++) :: [a] -> [a] -> [a]

So ++ can only be applied to lists and [char] is a list of chars.

Mean while if you want to convert this Int value to String/[Char] you may use show

Prelude> :t show
show :: Show a => a -> String

This mean show is capable of taking certain types as denoted by 'a' and returning String.

So to fix the error you may use otherwise = show(mod n b) ++ int2Base (div n b) b

This will make sure you match the function type with a list of strings

int2Base :: Int -> Int -> String
int2Base n b
  |n == 0 = ['0']
  |otherwise = show(mod n b) ++ int2Base (div n b) b

(I've used ['0'] just to show how String in double quotes maintains [chars] type