Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that sets an exponent in string in Julia

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.

like image 444
Tanj Avatar asked Dec 22 '21 15:12

Tanj


People also ask

How to use Julia exponential root function?

Julia Exponential Root is used to find the exponent of a number. In this tutorial, we will learn how to use the exponential function, exp() with examples. If the argument to the exponential function is near zero and you require an accurate computation of the exponential function, use expm1(x) function. Examples of Julia Exponential Root function.

How do you write a function in Julia?

The basic syntax for defining functions in Julia is: julia> function f (x,y) x + y end f (generic function with 1 method) This function accepts two arguments x and y and returns the value of the last expression evaluated, which is x + y. There is a second, more terse syntax for defining a function in Julia.

How many arguments does a function have in Julia?

This function accepts two arguments x and y and returns the value of the last expression evaluated, which is x + y. There is a second, more terse syntax for defining a function in Julia.

How to concatenate strings in Julia?

Concatenation of Strings in Julia can be done in a very simple way by using string (str1, str2, ...) function. Interpolation of Strings is the process of substituting variable values or expressions in a String.


2 Answers

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)

like image 198
Bogumił Kamiński Avatar answered Oct 22 '22 01:10

Bogumił Kamiński


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
like image 35
longemen3000 Avatar answered Oct 22 '22 03:10

longemen3000