Advertisement
Guest User

Untitled

a guest
Apr 5th, 2020
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module BC where
  2.  
  3. --indexInto returns the index of the first argument in a list
  4. --(don't worry about error checking -- can assume in list)
  5. indexInto :: Eq a => a -> [a] -> Int
  6. indexInto x ys = fst $ head $ filter ((== x) . snd) $ zip [0..] ys
  7.  
  8. --converts a character into its corresponding integer value
  9. -- e.g. '0' to 0, 'A' to 10, 'Z' to 35
  10. -- like hex, except with more digits
  11. -- (consider using elem -- look it up)
  12. dig2Int :: Char -> Int
  13. dig2Int dChar
  14.   | elem dChar ['0'..'9'] = indexInto dChar ['0'..'9']
  15.   | elem dChar ['A'..'Z'] = 10 + indexInto dChar ['A'..'Z']
  16.   | otherwise             = -1
  17.  
  18. --converts an integer in range 0..35 into its
  19. -- corresponding digit (0,1..Z)
  20. -- again, don't care about ints out of bounds
  21. num2char :: Int -> Char
  22. num2char n
  23.   | 0 <= n && n < 10 = ['0'..'9'] !! n
  24.   | otherwise        = ['A'..'Z'] !! (n-10)
  25.  
  26. --converts an integer value to a string representing
  27. -- the number in base b
  28. -- suggest looking up repeated division strategy
  29. -- for how to convert base 10 to binary and
  30. -- then generalize
  31. int2Base :: Int -> Int -> String
  32. int2Base n b
  33.   | n < b     = [num2char n]
  34.   | otherwise = int2Base (n `div` b) b ++ [num2char (n `mod` b)]
  35.  
  36. --convert a number string in base b1 into an Int
  37. -- can assume input is valid
  38. valNumString :: String -> Int -> Int
  39. valNumString xs b1 = sum $ zipWith (*) (map (b1^) [0..]) (reverse $ map dig2Int xs)
  40.  
  41. --convert String of numbers in base b1 into
  42. -- equivalent value in base b2, as a String
  43. -- again, all input will be valid
  44. convert :: String -> Int -> Int -> String
  45. convert numString b1 b2 = int2Base (valNumString numString b1) b2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement