Function that sets an exponent in string in Julia
Asked Answered
D

2

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.

Dewhurst answered 22/12, 2021 at 15:44 Comment(2)
Curious: what you need it for?Cannibal
I used it to make the legend in the package BenchmarkProfiles.jlDewhurst
T
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)

Threefold answered 22/12, 2021 at 16:7 Comment(2)
One step better (possibly) is codes = [x for x in "⁰¹²³⁴⁵⁶⁷⁸⁹"] with map(c -> codes[c-'0'+1], s)Alphitomancy
It would be faster to hardcode a tuple ('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹') as it would be non-allocating, but I thought it would be less clear.Sibilla
E
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
Eakin answered 22/12, 2021 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.