12

Is there a platform function that will do the following?

convertBase :: (Num a, Num b) => Int -> Int -> [a] -> [b]

Convert a number from base 'a' to base 'b' where each list item is a digit in the number. for example:

convertBase 2 10 [1,1,0,1] = [1, 3]

I hope that makes sense, let me know if i can clear anything up

3 Answers3

15

Using the digits package from Hackage:

import Data.Digits (digits, unDigits)

convertBase :: Integral a => a -> a -> [a] -> [a]
convertBase from to = digits to . unDigits from

You can add a fromIntegral in there if you need the input and output types to be different. Also, the Integral constraint makes more sense than Num, since you probably don't want to deal with complex or floating-point digits.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • The resulting function accepts a list of integrals. If I create a `decToBin = convertBase 10 2`, what does it mean to use `decToBin [10,10]`? – CMCDragonkai May 24 '15 at 10:53
  • Oh I found out that `decToBin [10, 10]` is the same as `decToBin [1010]`. It just concatenates all the numbers in the list. – CMCDragonkai May 24 '15 at 10:56
8

The closest thing in the haskell platform is from module Numeric:

readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS

fromBase :: Int -> String -> Int
fromBase base = fst . head . readInt base ((<base).digitToInt) digitToInt

toBase :: Int -> Int -> String
toBase base num = showIntAtBase base intToDigit num ""

fromBaseToBase :: Int -> Int -> String -> String
fromBaseToBase from to = toBase to . fromBase from
APerson
  • 8,140
  • 8
  • 35
  • 49
Riccardo T.
  • 8,907
  • 5
  • 38
  • 78
2

Couple of ideas:

  • use showIntAtBase or Text.printf to convert to a string, and convert back to a different base
  • write it yourself -- easier when one base is always a multiple of the other

Here is a link that might help you: http://rosettacode.org/wiki/Non-decimal_radices/Convert#Haskell -- Non-decimal radices/Convert

j13r
  • 2,576
  • 2
  • 21
  • 28