Guest User

Untitled

a guest
Apr 27th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. (ns cljutils.math
  2. "Functions for doing stuff")
  3.  
  4. (defn- powers-of [n]
  5. "For given base n, create lazy sequence of powers of n"
  6. (iterate #(* % n) 1))
  7.  
  8. (defn- char-range [& limits]
  9. "Given an even number of limit characters, creates an inclusive character sequence"
  10. (apply concat (map (fn [[start end]]
  11. ;; Partition pairs, convert to ints, map back to chars
  12. (map char (range (int start)
  13. (inc (int end))))) (partition 2 limits))))
  14.  
  15. (defn- syms-vals [base]
  16. "Given a base, return the number of characters necessary for representation. Limit is 36 (0-z)"
  17. ;; Take only the necessary number of characters for the base, then zip with decimal values
  18. (let [syms (take base (char-range \0 \9 \A \Z))
  19. vals (range 0 (inc (count syms)))]
  20. (zipmap syms vals)))
  21.  
  22. (defn- prep-str [s base]
  23. "Maps characters to values, ignoring unrecognized characters."
  24. (let [charmap (syms-vals base)]
  25. ;; Convert to upper case, filter out unknown chars, map to values
  26. (map charmap (filter #(contains? charmap %) (reverse (-> s .toUpperCase))))))
  27.  
  28. (defn strton [s base]
  29. "Given string s and int base, convert to integer"
  30. ;; Multiply pairs of powers and values, then sum them
  31. (reduce + (map (fn [[pow val]]
  32. ;; Create pairs of powers and values
  33. (* pow val)) (partition 2 (interleave (powers-of base) (prep-str s base))))))
  34.  
  35. ;;; Binary
  36. (strton "0111010110100" 2)
  37. ;;; octal
  38. (strton "7264" 8)
  39. ;;; hex with uppercase
  40. (strton "EB4" 16)
  41. ;;; hex
  42. (strton "eb4" 16)
  43. ;;; hex with spurious chars
  44. (strton "eb4" 16)
  45. ;;; hex with preceding 0x
  46. (strton "0xEB4" 16)
  47. ;;; undecimal
  48. (strton "5a2", 11)
Add Comment
Please, Sign In to add comment