Julia - Specify arguments to input of another function

Viewed 97

I know in Julia I can do parse(BigFloat, x) where x might be a string or the result of readline(). However, what if I want to specify a precision to my BigFloat within the parse function?

Like you can do BigFloat(pi, precision = 50).

I believe this can be generalized to cases where you put a function, a constructor or a type into another function and you want to specify arguments of the former one.

1 Answers

For general constructors and parsing there won't be a solution for this, as the parsing might need to use implementation details. But since BigFloat implementors have forseen this use case, there is a method for the constructor taking an AbstractString and the precision:

julia> BigFloat("3.141592653589793238462643383279502884197169399375105820974944592307816406286198")
3.141592653589793238462643383279502884197169399375105820974944592307816406286198

julia> BigFloat("3.141592653589793238462643383279502884197169399375105820974944592307816406286198", precision = 50)
3.1415926535897931

julia> parse(Float64, "3.141592653589793238462643383279502884197169399375105820974944592307816406286198")
3.141592653589793

The generalization you imagine is also not possible; I think you have a misconception there. The first argument of parse is not trated as a callable object, but a type used only for dispatch. So you cannot just circumvent construction by passing an anonymous function:

julia> parse(f -> BigFloat(f, precision=50),  "3.141592653589793238462643383279502884197169399375105820974944592307816406286198")
ERROR: MethodError: no method matching parse(::var"#1#2", ::String)
Closest candidates are:
  parse(::Type{T}, ::AbstractString; base) where T<:Integer at parse.jl:237
  parse(::Type{T}, ::AbstractString; kwargs...) where T<:Real at parse.jl:376
  parse(::Type{T}, ::AbstractString) where T<:Complex at parse.jl:378
  ...
Stacktrace:
 [1] top-level scope at REPL[10]:1

Why is that? Because if it were just parsing a Float64 and passing that into the BigFloat constructor, the "bigness" would be in vain -- the precision gets lost before the number reaches BigFloat. You need to go from the string directly to the internal representation.

Related