在 Julia 中设置字符串指数的函数

Function that sets an exponent in string in Julia

我正在寻找执行以下渲染的函数:

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

我试过了 f(s) = "2\^($s)" 但这似乎不是一个有效的指数,因为我不能 TAB。

您可以尝试例如:

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¹⁵"

(我没有针对速度对其进行优化,但我希望它足够快,以便于阅读代码)

这个应该会快一点,并且使用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

在这种情况下,我使用了 replace 可以接受 Pair{collection,function} 的事实:

if char in collection
  replace(char,function(char))
end