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

前端 未结 6 677
伪装坚强ぢ
伪装坚强ぢ 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:48

    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.

提交回复
热议问题