Created
June 8, 2011 16:47
-
-
Save epsilonhalbe/1014802 to your computer and use it in GitHub Desktop.
tTransformer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Transformer (dec2bin, bin2dec, dec2hex, hex2dec, num2letters, letters2num) where | |
dec2bin :: Int -> [Int] | |
dec2bin n | |
|n==0 = [] | |
|otherwise = (dec2bin (div n 2))++[mod n 2] | |
bin2dec :: [Int] -> Int | |
bin2dec bs = foldl1 (\x y ->x*2+y) bs | |
dec2hex :: Int -> String | |
dec2hex n | |
|n==0 = "" | |
|otherwise = (dec2hex (div n 16))++(num2letters (mod n 16)) | |
hex2dec :: String -> Int | |
hex2dec bs = foldl1 (\x y ->x*16+y) (map letters2num bs) | |
num2letters :: Int -> String | |
num2letters x | |
|x == 10 = "a" | |
|x == 11 = "b" | |
|x == 12 = "c" | |
|x == 13 = "d" | |
|x == 14 = "e" | |
|x == 15 = "f" | |
|x >= 16 = "error" | |
|otherwise = show x | |
letters2num :: Char -> Int | |
letters2num x | |
|x == '0' = 00 | |
|x == '1' = 01 | |
|x == '2' = 02 | |
|x == '3' = 03 | |
|x == '4' = 04 | |
|x == '5' = 05 | |
|x == '6' = 06 | |
|x == '7' = 07 | |
|x == '8' = 08 | |
|x == '9' = 09 | |
|x == 'a' = 10 | |
|x == 'b' = 11 | |
|x == 'c' = 12 | |
|x == 'd' = 13 | |
|x == 'e' = 14 | |
|x == 'f' = 15 | |
|otherwise = 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import TAP | |
import Transformer | |
main = runTests $ do | |
planTests 4 | |
is (dec2bin 10) [1,0,1,0] $ Just "decimal to binary conversion" | |
is (bin2dec [1,0,1,0]) 10 $ Just "binary to decimal conversion" | |
is (dec2hex 1234) "4d2" $ Just "decimal to hexadecimal conversion" | |
is (hex2dec "4d2") 1234 $ Just "hexadecimal to decimal conversion" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment