point8 / data-science-learning-paths

Practical data science courses
Other
23 stars 3 forks source link

+ Julia packaging exercise: Function with external dependency #23

Open clstaudt opened 1 month ago

clstaudt commented 1 month ago

Adding a Function with an External Package Dependency

Let's say you want to add a function that generates a sequence of prime numbers using the Primes package.

Create a new file (e.g., prime_sequence.jl) in your package's src directory and add the following code:

using Primes

function prime_sequence(n)
    primes = []
    for i in 1:n
        push!(primes, nextprime(i))
    end
    return primes
end

This function uses the nextprime function from the Primes package to generate a sequence of prime numbers.

Update Your Package's Project.toml File

Run the following command in your package's directory to update the Project.toml file:

julia --project=. -e "Pkg.resolve()"

This will update the Project.toml file to include the Primes package as a dependency.

Example Use Case

You can now use the prime_sequence function in your package:

julia> using MyPackage

julia> prime_sequence(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

To use the latest version of a dependency, you can specify the dependency without a version range. For example:

[deps]
Primes = ""

This tells Julia to use the latest version of the Primes package.

Alternatively, you can use the * wildcard to specify the latest version:

[deps]
Primes = "*"

Both of these approaches will use the latest version of the Primes package.