转换数字库 [英] Converting number base
本文介绍了转换数字库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个平台函数可以执行以下操作?
Is there a platform function that will do the following?
convertBase :: (Num a, Num b) => Int -> Int -> [a] -> [b]
将数字从基数'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
推荐答案
使用 digits 来自Hackage的软件包:
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
您可以从<积分中添加 in那里如果你需要输入和输出类型是不同的。此外,
Integral
约束比 Num
更有意义,因为您可能不想处理复杂或浮动点数字。
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.
这篇关于转换数字库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文