Base58Check encoding: Difference between revisions

Content added Content deleted
m (→‎version 3: aligned comment with assignment value.)
Line 417: Line 417:
and for bulk encoding, Array access would be one of various slightly faster alternatives to recursive subscripting of linked lists:
and for bulk encoding, Array access would be one of various slightly faster alternatives to recursive subscripting of linked lists:
{{Trans|Python}}
{{Trans|Python}}
<lang Haskell>import Data.Array (Array, (!), listArray)
<lang Haskell>import Data.Array (Array, listArray, (!))
import Numeric (showHex, showIntAtBase)
import Numeric (showHex, showIntAtBase)


------------------- BASE58CHECK ENCODING -----------------
base58Encode

:: (Integral a, Show a)
base58Encode ::
=> a -> String
(Integral a, Show a) =>
a ->
String
base58Encode =
base58Encode =
baseEncode $
baseEncode $
listArray (0, 57) $
listArray (0, 57) $
[('1', '9'), ('A', 'H'), ('J', 'N'), ('P', 'Z'), ('a', 'k'), ('m', 'z')] >>=
[ ('1', '9'),
('A', 'H'),
uncurry enumFromTo
('J', 'N'),
('P', 'Z'),
('a', 'k'),
('m', 'z')
]
>>= uncurry enumFromTo


baseEncode
baseEncode ::
:: (Show a, Integral a)
(Show a, Integral a) =>
=> Array Int Char -> a -> String
Array Int Char ->
a ->
baseEncode cs n = showIntAtBase (fromIntegral $ length cs) (cs !) n []
String
baseEncode cs n =
showIntAtBase
(fromIntegral $ length cs)
(cs !)
n
[]


-- TEST ---------------------------------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main =
main =
putStrLn $
putStrLn $
fTable
fTable
"Base 58 encoding:\n"
"Base 58 encoding:\n"
(\x -> '0' : 'x' : showHex x [])
--(\x -> '0' : 'x' : showHex x [])
(("0x" <>) . flip showHex [])
base58Encode
id
base58Encode
id
[ 25420294593250030202636073700053352635053786165627414518
[ 25420294593250030202636073700053352635053786165627414518,
, 0x61
, 0x626262
0x61,
, 0x636363
0x626262,
0x636363,
, 0x73696d706c792061206c6f6e6720737472696e67
0x73696d706c792061206c6f6e6720737472696e67,
, 0x516b6fcd0f
0x516b6fcd0f,
, 0xbf4f89001e670274dd
0xbf4f89001e670274dd,
, 0x572e4794
0x572e4794,
, 0xecac89cad93923c02321
0xecac89cad93923c02321,
, 0x10c8511e
]
0x10c8511e
]


-- OUTPUT FORMATTING --------------------------------------
-------------------- OUTPUT FORMATTING -------------------
fTable ::
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
String ->
(a -> String) ->
(b -> String) ->
(a -> b) ->
[a] ->
String
fTable s xShow fxShow f xs =
fTable s xShow fxShow f xs =
let w = maximum $ fmap length (xShow <$> xs)
let w = maximum $ fmap length (xShow <$> xs)
rjust n c s = drop (length s) (replicate n c ++ s)
rjust n c = (drop . length) <*> (replicate n c <>)
in unlines $
in unlines $
s :
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</lang>
fmap
( ((<>) . rjust w ' ' . xShow)
<*> ((" -> " <>) . fxShow . f)
)
xs</lang>
{{Out}}
{{Out}}
<pre>Base 58 encoding:
<pre>Base 58 encoding: