Hello, I am using functions to read data, apply a certain function and then use a function to write results. I have not been able to figure out the correct way of passing one function as an argument to another function, and how to use functions to read and write data. When I try to run the program it does not seem to do anything.
I have given some examples below regarding what I am trying to do. I would like to understand the correct way of doing it. Specifically, I would like to know:
how to use functions to read data, apply some functions, and then print the results? If I use functions in this manner then its doesn’t seem to do anything, but if I write the code as a script then it works fine.
using CV
function read_data()
# Read data
x = Matrix{Float64}(CSV.read("./filename.csv")
y = Matrix{Float64}(CSV.read("./filename2.csv")
return x, y
end
const z = 1
function f(read_data::Function,z)
# Calculate something using the data
x, y = read_data()
P= x + y+z
return P
end
function write_results(f::Function)
Result = f(read_data::Function,z)
CSV.write("FileSaveName.csv",DataFrame(Addition=Result,X=x,Y=y,Z=z))
return println("Results saved in FileSaveName.csv")
end
function run_model()
P= f(read_data::Function,write_results::(f::Function))
end
This is a really unusual way of organizing your code. I would probably do something like
function read_data(file_x, file_y)
# Read data
x = Matrix{Float64}(CSV.read(file_x))
y = Matrix{Float64}(CSV.read(file_y))
x, y
end
function f(x, y, z)
# Calculate something using the data
x + y + z
end
function write_results(filename; result, x, y, z)
CSV.write(filename, DataFrame(Addition=result,X=x,Y=y,Z=z))
return println("Results saved in $(filename)")
end
function run_model(file_x, file_y, z, file_result)
x, y = read_data(file_x, file_y)
P = f(x, y, z)
write_results(file_result; result = P, x = x, y = y, z = z)
end
# runtime code
const z = 1
run_model("./filename.csv", "./filename2.csv", z, "FileSaveName.csv")
(Note that this is just a schematic rewrite and may contain typos.) That is, I would
- pass values, not functions,
- not hardcode filenames,
- organize the main computation into
run_model
with helper functions
7 Likes
Thank you! That makes sense to me.
One thing I would like to check is that in the actual code I have at least 10 different CSV files to read the data from. My little understanding of programming is that it is not considered a good practice to pass too many arguments to a function i.e. read_data(...)
and run_model(...)
functions here.
Do you have any suggestions for this?
I was thinking that maybe having a function which defines all the names of the files (including path to read from) and then that function can be passed on as an argument to the run_model(...)
function.
Maybe pass those filenames as a vector and iterate?
1 Like
Thanks. I will look in to it
1 Like