5

I am looking for a function that does the following rending:

f("2") = 2²
f("15") = 2¹⁵

I tried f(s) = "2\^($s)" but this doesn't seem to be a valid exponent as I can't TAB.

Tanj
  • 442
  • 2
  • 9

2 Answers2

7

You can try e.g.:

julia> function f(s::AbstractString)
           codes = Dict(collect("1234567890") .=> collect("¹²³⁴⁵⁶⁷⁸⁹⁰"))
           return "2" * map(c -> codes[c], s)
       end
f (generic function with 1 method)

julia> f("2")
"2²"

julia> f("15")
"2¹⁵"

(I have not optimized it for speed, but I hope this is fast enough with the benefit of being easy to read the code)

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • One step better (possibly) is `codes = [x for x in "⁰¹²³⁴⁵⁶⁷⁸⁹"]` with `map(c -> codes[c-'0'+1], s)` – Oscar Smith Dec 22 '21 at 16:09
  • 2
    It would be faster to hardcode a tuple `('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹')` as it would be non-allocating, but I thought it would be less clear. – Bogumił Kamiński Dec 22 '21 at 16:43
1

this should be a little faster, and uses replace:

function exp2text(x) 
  two = '2'
  exponents = ('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹') 
  #'⁰':'⁹' does not contain the ranges 
  exp = replace(x,'0':'9' =>i ->exponents[Int(i)-48+1])
  #Int(i)-48+1 returns the number of the character if the character is a number
  return two * exp
end

in this case, i used the fact that replace can accept a Pair{collection,function} that does:

if char in collection
  replace(char,function(char))
end
longemen3000
  • 1,273
  • 5
  • 14