Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module BC where
- --indexInto returns the index of the first argument in a list
- --(don't worry about error checking -- can assume in list)
- indexInto :: Eq a => a -> [a] -> Int
- indexInto x ys = fst $ head $ filter ((== x) . snd) $ zip [0..] ys
- --converts a character into its corresponding integer value
- -- e.g. '0' to 0, 'A' to 10, 'Z' to 35
- -- like hex, except with more digits
- -- (consider using elem -- look it up)
- dig2Int :: Char -> Int
- dig2Int dChar
- | elem dChar ['0'..'9'] = indexInto dChar ['0'..'9']
- | elem dChar ['A'..'Z'] = 10 + indexInto dChar ['A'..'Z']
- | otherwise = -1
- --converts an integer in range 0..35 into its
- -- corresponding digit (0,1..Z)
- -- again, don't care about ints out of bounds
- num2char :: Int -> Char
- num2char n
- | 0 <= n && n < 10 = ['0'..'9'] !! n
- | otherwise = ['A'..'Z'] !! (n-10)
- --converts an integer value to a string representing
- -- the number in base b
- -- suggest looking up repeated division strategy
- -- for how to convert base 10 to binary and
- -- then generalize
- int2Base :: Int -> Int -> String
- int2Base n b
- | n < b = [num2char n]
- | otherwise = int2Base (n `div` b) b ++ [num2char (n `mod` b)]
- --convert a number string in base b1 into an Int
- -- can assume input is valid
- valNumString :: String -> Int -> Int
- valNumString xs b1 = sum $ zipWith (*) (map (b1^) [0..]) (reverse $ map dig2Int xs)
- --convert String of numbers in base b1 into
- -- equivalent value in base b2, as a String
- -- again, all input will be valid
- convert :: String -> Int -> Int -> String
- convert numString b1 b2 = int2Base (valNumString numString b1) b2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement