是否有平台功能可以执行以下操作?
convertBase :: (Num a, Num b) => Int -> Int -> [a] -> [b]
Run Code Online (Sandbox Code Playgroud)
将数字从基数'a'转换为基数'b',其中每个列表项是数字中的数字.例如:
convertBase 2 10 [1,1,0,1] = [1, 3]
Run Code Online (Sandbox Code Playgroud)
我希望这是有道理的,如果我能清除任何事情,请告诉我
ham*_*mar 14
使用Hackage中的数字包:
import Data.Digits (digits, unDigits)
convertBase :: Integral a => a -> a -> [a] -> [a]
convertBase from to = digits to . unDigits from
Run Code Online (Sandbox Code Playgroud)
fromIntegral
如果需要输入和输出类型不同,可以在其中添加.此外,Integral
约束更有意义Num
,因为您可能不想处理复杂或浮点数字.
haskell平台中最接近的是模块Numeric:
readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS
fromBase :: Int -> String -> Int
fromBase base = fst . head . readInt base ((<base).digitToInt) digitToInt
toBase :: Int -> Int -> String
toBase base num = showIntAtBase base intToDigit num ""
fromBaseToBase :: Int -> Int -> String -> String
fromBaseToBase from to = toBase to . fromBase from
Run Code Online (Sandbox Code Playgroud)