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

前端 未结 6 676
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 18:11

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.

6条回答
  •  隐瞒了意图╮
    2021-01-01 18:23

    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
    

提交回复
热议问题