Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string representing a binary number to a base 10 string haskell

Tags:

haskell

I have the string "1001" and I want the string "9".

The numeric library has the (rather clunky) showIntAtBase, but I haven't been able to find the opposite.

like image 428
Johanna Larsson Avatar asked May 07 '11 14:05

Johanna Larsson


2 Answers

It's been a while since the original post but, for future readers' benefit, I would use the following:

import Data.Char (digitToInt)
import Data.List (foldl')

toDec :: String -> Int
toDec = foldl' (\acc x -> acc * 2 + digitToInt x) 0

No need to slow things down by using ^, reverse, zipWith, length, etc.

Also, using a strict fold reduces memory requirements.

like image 135
iceman Avatar answered Oct 07 '22 21:10

iceman


Here is more or less what you were looking for from Prelude. From Numeric:

(NB: readInt is the "dual" of showIntAtBase, and readDec is the "dual" of showInt. The inconsistent naming is a historical accident.)

import Data.Char  (digitToInt)
import Data.Maybe (listToMaybe)
import Numeric    (readInt)

readBin :: Integral a => String -> Maybe a
readBin = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
-- readBin "1001" == Just 9
like image 30
ACoolie Avatar answered Oct 07 '22 19:10

ACoolie