Functions usage

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}("./filename.csv")
y = Matrix{Float64}("./filename2.csv")
return x, y
const z = 1
function f(read_data::Function,z)
# Calculate something using the data    
x, y = read_data()
P=  x + y+z
return P
function write_results(f::Function)
Result = f(read_data::Function,z)
return println("Results saved in FileSaveName.csv")
function run_model()
 P= f(read_data::Function,write_results::(f::Function))

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}(
    y = Matrix{Float64}(
    x, y

function f(x, y, z)
    # Calculate something using the data    
    x + y + z

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)")

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)

# 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

  1. pass values, not functions,
  2. not hardcode filenames,
  3. organize the main computation into run_model with helper functions

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