How to understand this "typemaker" function?

I read a post on towardsdatascience:
https://towardsdatascience.com/3-smooth-syntactical-tips-for-julia-65ddf577f071

It used something that looks to me like an anonymous type, which I don’t know exists:

mutable struct car_stats
    distance
    time
    speed
end
honda_civic = car_stats(25, 40, nothing)

function speed(carstat)
    mph = carstat.distance / carstat.time
    return(mph)
end

typemaker(speedfunc,civic) = ()->(speedfunc;civic)

d = typemaker(speed,honda_civic)

d.speedfunc(d.civic)

The question is, why would this even work? What is the anonymous function’s return value (speedfunc;civic)? Why a function that returns this thing can be used as if it’s a user defined type (struct)?

An explanation and/or link to the relevant document will be appreciated!

This example is somewhat contrived…

It works by creating a closure which is an anonymous function. Internally, anonymous functions capture the various variables referenced within.

Here even though the anonymous function ()->(speedfunc;civic) simply returns civic (it doesn’t do anything with speedfunc), both variables are still captured (and accessible by dot notation, like structs).

For this example, there is no reason to have the typemaker function which returns an anonymous function. All of the info is already captured in the type car_stats. Instead of calling d.speedfunc(d.civic), just call speed(honda_civic)

If there is a need for some object to store the speedfunc and the car, as is done by the closure, a better way would be to simply create a tuple (speedfunc,civic), or simply create another type.

3 Likes

Thank you! This is quite interesting…