# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .jl
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Julia 1.5.2
#     language: julia
#     name: julia-1.5
# ---

# # Using other languages

# One of the biggest difficulties that appear when changing from another languages to Julia is not being able to keep using all the code that we have developed in other languages. However, Julia allows to invoke code that is written in other languages such as Python, R or C.

# ## Python

# You can import any python package using the *PyCall* package.

using PyCall

math = PyCall.pyimport("math")

math.sin(math.pi / 4) 

# We can also write our own Python code as follows

py""" 
import math

def some_fancy_function(x):
    return math.sin(x)

"""

y = py"some_fancy_function(3)"

# If the above function was in a file called *fancy_functions.py*, you can call it as follows:
#
#     python_fancy_functions = pyimport("fancy_functions")
#     python_fancy_functions.some_fancy_function(3)

# ## R code

using RCall

# We can use the *rcall* function

r = rcall(:sum, Float64[1.0, 4.0, 6.0]) 

typeof(r)

typeof(r[1])

# The @rput allows you to put a Julia variable in the R context.

z = 5
@rput z

r = R"z+z"

# You can apply R functions on Julia variables

x = randn(10) # Julia variable

@rimport base as rbase 
rbase.sum([1,2,3])

@rlibrary boot 

R"t.test($x)"

# And the equivalent in Julia would be:

using HypothesisTests
OneSampleTTest(x)

# ## C and C++ code

# Calling standard libraries is easy:

?ccall

t = ccall(:clock, Int32, ())

# You can also wrap your own C code:

"""
#include <stdio.h>
int hello_world()
{
    printf("Hello, World!\n");
    return 0;
}

int hello_world_repeated(int n)
{
    for (int i = 0; i<n; i++){
        printf("Hello, World!\n");
    }
    return 0;
}

To compile:
> gcc -g -O -c c-code/hello_world.c 
> gcc -dynamiclib -o c-code/hello_world_lib.dylib c-code/hello_world.o

""";

ccall(("hello_world","$(pwd())/c-code/hello_world_lib.dylib"),
    Int64,
    (),)

ccall((:hello_world_repeated,"$(pwd())/hello_world_lib.dylib"),
    Int64,
    (Int64,),
    10)





StarcoderdataJupyterScriptsDedupFiltered