将表示二进制数字的字符串转换为基本10字符串haskell [英] Convert a string representing a binary number to a base 10 string haskell

查看:372
本文介绍了将表示二进制数字的字符串转换为基本10字符串haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串1001,我想要字符串9。

数字库有(相当笨拙的)showIntAtBase,但我没有能够找到相反的结果。

解决方案

这里或多或少是你从Prelude中寻找的东西。
数字


(注意:readInt是showIntAtBase的双重,readDec是showInt的双重,不一致的命名是历史事故。)



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

readBin :: Integral a =>字符串 - >也许
readBin = fmap fst。 listToMaybe。 readInt 2(`elem`01)digitToInt
- readBin1001==只是9


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.

解决方案

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

这篇关于将表示二进制数字的字符串转换为基本10字符串haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆