11

次のことを行うプラットフォーム機能はありますか?

convertBase :: (Num a, Num b) => Int -> Int -> [a] -> [b]

各リスト項目が数値の数字である基数 'a' から基数 'b' に数値を変換します。例えば:

convertBase 2 10 [1,1,0,1] = [1, 3]

それが理にかなっていることを願っています。何か解決できることがあれば教えてください

4

3 に答える 3

15

Hackageのdigitsパッケージを使用する:

import Data.Digits (digits, unDigits)

convertBase :: Integral a => a -> a -> [a] -> [a]
convertBase from to = digits to . unDigits from

fromIntegral入力と出力の型を異なるものにする必要がある場合は、そこに a を追加できます。また、おそらく複雑な数字や浮動小数点数を扱いたくないので、Integral制約は よりも理にかなっています。Num

于 2012-04-05T12:45:34.340 に答える
8

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
于 2012-04-05T12:49:58.587 に答える
2

いくつかのアイデア:

  • showIntAtBase または Text.printf を使用して文字列に変換し、別の基数に戻す
  • 自分で書く - 1 つのベースが常に他のベースの倍数である場合は簡単

ここにあなたを助けるかもしれないリンクがあります: http://rosettacode.org/wiki/Non-decimal_radices/Convert#Haskell -- Non-decimal radices/Convert

于 2012-04-05T12:31:35.683 に答える