Julia Programming – Data Frames ”; Previous Next DataFrame may be defined as a table or spreadsheet which we can be used to sort as well as explore a set of related data values. In other words, we can call it a smarter array for holding tabular data. Before we use it, we need to download and install DataFrame and CSV packages as follows − (@v1.5) pkg> add DataFrames (@v1.5) pkg> add CSV To start using the DataFrames package, type the following command − julia> using DataFrames Loading data into DataFrames There are several ways to create new DataFrames (which we will discuss later in this section) but one of the quickest ways to load data into DataFrames is to load the Anscombe dataset. For better understanding, let us see the example below − anscombe = DataFrame( [10 10 10 8 8.04 9.14 7.46 6.58; 8 8 8 8 6.95 8.14 6.77 5.76; 13 13 13 8 7.58 8.74 12.74 7.71; 9 9 9 8 8.81 8.77 7.11 8.84; 11 11 11 8 8.33 9.26 7.81 8.47; 14 14 14 8 9.96 8.1 8.84 7.04; 6 6 6 8 7.24 6.13 6.08 5.25; 4 4 4 19 4.26 3.1 5.39 12.5; 12 12 12 8 10.84 9.13 8.15 5.56; 7 7 7 8 4.82 7.26 6.42 7.91; 5 5 5 8 5.68 4.74 5.73 6.89]); julia> rename!(anscombe, [Symbol.(:N, 1:4); Symbol.(:M, 1:4)]) 11×8 DataFrame │ Row │ N1 │ N2 │ N3 │ N4 │ M1 │ M2 │ M3 │ M4 │ │ │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ 10.0 │ 10.0 │ 10.0 │ 8.0 │ 8.04 │ 9.14 │ 7.46 │ 6.58 │ │ 2 │ 8.0 │ 8.0 │ 8.0 │ 8.0 │ 6.95 │ 8.14 │ 6.77 │ 5.76 │ │ 3 │ 13.0 │ 13.0 │ 13.0 │ 8.0 │ 7.58 │ 8.74 │ 12.74 │ 7.71 │ │ 4 │ 9.0 │ 9.0 │ 9.0 │ 8.0 │ 8.81 │ 8.77 │ 7.11 │ 8.84 │ │ 5 │ 11.0 │ 11.0 │ 11.0 │ 8.0 │ 8.33 │ 9.26 │ 7.81 │ 8.47 │ │ 6 │ 14.0 │ 14.0 │ 14.0 │ 8.0 │ 9.96 │ 8.1 │ 8.84 │ 7.04 │ │ 7 │ 6.0 │ 6.0 │ 6.0 │ 8.0 │ 7.24 │ 6.13 │ 6.08 │ 5.25 │ │ 8 │ 4.0 │ 4.0 │ 4.0 │ 19.0 │ 4.26 │ 3.1 │ 5.39 │ 12.5 │ │ 9 │ 12.0 │ 12.0 │ 12.0 │ 8.0 │ 10.84 │ 9.13 │ 8.15 │ 5.56 │ │10 │ 7.0 │ 7.0 │ 7.0 │ 8.0 │ 4.82 │ 7.26 │ 6.42 │ 7.91 │ │11 │ 5.0 │ 5.0 │ 5.0 │ 8.0 │ 5.68 │ 4.74 │ 5.73 │ 6.89 │ We assigned the DataFrame to a variable named Anscombe, convert them to an array and then rename columns. Collected Datasets We can also use another dataset package named RDatasets package. It contains several other famous datasets including Anscombe’s. Before we start using it, we need to first download and install it as follows − (@v1.5) pkg> add RDatasets To start using this package, type the following command − julia> using DataFrames julia> anscombe = dataset(“datasets”,”anscombe”) 11×8 DataFrame │ Row │ X1 │ X2 │ X3 │ X4 │ Y1 │ Y2 │ Y3 │ Y4 │ │ │ Int64 │ Int64 │ Int64 │ Int64 │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼───────┼───────┼───────┼───────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ 10 │ 10 │ 10 │ 8 │ 8.04 │ 9.14 │ 7.46 │ 6.58 │ │ 2 │ 8 │ 8 │ 8 │ 8 │ 6.95 │ 8.14 │ 6.77 │ 5.76 │ │ 3 │ 13 │ 13 │ 13 │ 8 │ 7.58 │ 8.74 │ 12.74│ 7.71 │ │ 4 │ 9 │ 9 │ 9 │ 8 │ 8.81 │ 8.77 │ 7.11 │ 8.84 │ │ 5 │ 11 │ 11 │ 11 │ 8 │ 8.33 │ 9.26 │ 7.81 │ 8.47 │ │ 6 │ 14 │ 14 │ 14 │ 8 │ 9.96 │ 8.1 │ 8.84 │ 7.04 │ │ 7 │ 6 │ 6 │ 6 │ 8 │ 7.24 │ 6.13 │ 6.08 │ 5.25 │ │ 8 │ 4 │ 4 │ 4 │ 19 │ 4.26 │ 3.1 │ 5.39 │ 12.5 │ │ 9 │ 12 │ 12 │ 12 │ 8 │ 10.84 │ 9.13 │ 8.15 │ 5.56 │ │ 10 │ 7 │ 7 │ 7 │ 8 │ 4.82 │ 7.26 │ 6.42 │ 7.91 │ │ 11 │ 5 │ 5 │ 5 │ 8 │ 5.68 │ 4.74 │ 5.73 │ 6.89 │ Empty DataFrames We can also create DataFrames by simply providing the information about rows, columns as we give in an array. Example julia> empty_df = DataFrame(X = 1:10, Y = 21:30) 10×2 DataFrame │ Row │ X │ Y │ │ │ Int64 │ Int64 │ ├─────┼───────┼───────┤ │ 1 │ 1 │ 21 │ │ 2 │ 2 │ 22 │ │ 3 │ 3 │ 23 │ │ 4 │ 4 │ 24 │ │ 5 │ 5 │ 25 │ │ 6 │ 6 │ 26 │ │ 7 │ 7 │ 27 │ │ 8 │ 8 │ 28 │ │ 9 │ 9 │ 29 │ │ 10 │ 10 │ 30 │ To create completely empty DataFrame, we only need to supply the Column Names and define their types as follows − julia> Complete_empty_df = DataFrame(Name=String[], W=Float64[], H=Float64[], M=Float64[], V=Float64[]) 0×5 DataFrame julia> Complete_empty_df = vcat(Complete_empty_df, DataFrame(Name=”EmptyTestDataFrame”, W=5.0, H=5.0, M=3.0, V=5.0)) 1×5 DataFrame │ Row │ Name │ W │ H │ M │ V │ │ │ String │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼────────────────────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ EmptyTestDataFrame │ 5.0 │ 5.0 │ 3.0 │ 5.0 │ julia> Complete_empty_df = vcat(Complete_empty_df, DataFrame(Name=”EmptyTestDataFrame2″, W=6.0, H=6.0, M=5.0, V=7.0)) 2×5 DataFrame │ Row │ Name │ W │ H │ M │ V │ │ │
Category: julia
Julia – Modules and Packages
Julia Programming – Modules and Packages ”; Previous Next The modules in Julia programming language are used to group together the related functions and other definitions. The structure of a module is given below − module ModuleName end We can define and put functions, type definitions, and so on in between above two lines. Installing Modules Julia’s package manager can be used to download and install a particular package. To enter the package manage from REPL, type ] (right bracket). Once entering the package manager, you need to type the following command − (@v1.5) pkg> add DataFrames Updating registry at `C:UsersLeekha.juliaregistriesGeneral` Resolving package versions… Updating `C:UsersLeekha.juliaenvironmentsv1.5Project.toml` [a93c6f00] + DataFrames v0.21.7 No Changes to `C:UsersLeekha.juliaenvironmentsv1.5Manifest.toml` The above command will add DataFrames package to Julia’s environment. The (@v1.5) in the prompt tells us that we are working in the default project, “v1.5”, in ~/.julia/environments/. Using Modules Once installed, it is time to start using the functions and definitions from the installed module. For this we need to tell Julia programming language to make code available for our current session. Use using statement which will accept the names of one or more installed modules. Example julia> using DataFrames [ Info: Precompiling DataFrames [a93c6f00-e57d-5684-b7b6-d8193f3e46c0] julia> empty_df = DataFrame(X = 1:10, Y = 21:30) 10×2 DataFrame │ Row │ X │ Y │ │ │ Int64 │ Int64 │ ├─────┼───────┼───────┤ │ 1 │ 1 │ 21 │ │ 2 │ 2 │ 22 │ │ 3 │ 3 │ 23 │ │ 4 │ 4 │ 24 │ │ 5 │ 5 │ 25 │ │ 6 │ 6 │ 26 │ │ 7 │ 7 │ 27 │ │ 8 │ 8 │ 28 │ │ 9 │ 9 │ 29 │ │ 10 │ 10 │ 30 │ Import Like using, import can also be used for modules. The only difference is that import lets you decide how you would like to access the functions inside the module. In the below example, we have two different functions in a module. Let us see how we can import them − Example julia> module first_module export foo1 function foo1() println(“this is first function”) end function foo2() println(“this is second function”) end end Main.first_module Now we need to use import to import this module − julia> import first_module julia> foo1() ERROR: foo1 not defined julia> first_module.foo1() ”this is first function” You can notice that the function foo1() can only be accessed if it is used with module prefix. It is because the first_module was loaded using import command rather than using command. Include What if you want to use the code from other files that are not contained in the modules? For this you can use include() function which will evaluate the contents of the file in the context of the current module. It will search the relative path of the source file from which it is called. Packages Use status command in Julia package environment to see all the packages you have installed. (@v1.5) pkg> status Status `C:UsersLeekha.juliaenvironmentsv1.5Project.toml` [336ed68f] CSV v0.7.7 [a93c6f00] DataFrames v0.21.7 [864edb3b] DataStructures v0.18.6 [7806a523] DecisionTree v0.10.10 [38e38edf] GLM v1.3.10 [28b8d3ca] GR v0.52.0 [86223c79] Graphs v0.10.3 [7073ff75] IJulia v1.21.3 [682c06a0] JSON v0.21.1 [91a5bcdd] Plots v1.6.8 [d330b81b] PyPlot v2.9.0 [ce6b1742] RDatasets v0.6.10 [3646fa90] ScikitLearn v0.6.2 [f3b207a7] StatsPlots v0.14.13 [b8865327] UnicodePlots v1.3.0 [112f6efa] VegaLite v1.0.0 Structure of a package As we know that Julia uses git for organizing as well controlling the packages. All the packages are stored with .ji prefix. Let us see the structure of Calculus package − Calculus.jl/ src/ Calculus.jl module Calculus import Base.ctranspose export derivative, check_gradient, … include(“derivative.jl”) include(“check_derivative.jl”) include(“integrate.jl”) end derivative.jl function derivative() … end … check_derivative.jl function check_derivative(f::…) … end … integrate.jl function adaptive_simpsons_inner(f::Funct … end … symbolic.jl export processExpr, BasicVariable, … import Base.show, … type BasicVariable <: AbstractVariable … end function process(x::Expr) … end … test/ runtests.jl using Calculus using Base.Test tests = [“finite_difference”, … for t in tests include(“$(t).jl”) end … finite_difference.jl @test … … Print Page Previous Next Advertisements ”;
Julia – Basic Operators
Julia – Basic Operators ”; Previous Next In this chapter, we shall discuss different types of operators in Julia. Arithmetic Operators In Julia, we get all the basic arithmetic operators across all the numeric primitive types. It also provides us bitwise operators as well as efficient implementation of comprehensive collection of standard mathematical functions. Following table shows the basic arithmetic operators that are supported on Julia’s primitive numeric types − Expression Name Description +x unary plus It is the identity operation. -x unary minus It maps values to their additive inverses. x + y binary plus It performs addition. x – y binary minus It performs subtraction. x * y times It performs multiplication. x / y divide It performs division. x ÷ y integer divide Denoted as x / y and truncated to an integer. x y inverse divide It is equivalent to y / x. x ^ y power It raises x to the yth power. x % y remainder It is equivalent to rem(x,y). !x negation It is negation on bool types and changes true to false and vice versa. The promotion system of Julia makes these arithmetic operations work naturally and automatically on the mixture of argument types. Example Following example shows the use of arithmetic operators − julia> 2+20-5 17 julia> 3-8 -5 julia> 50*2/10 10.0 julia> 23%2 1 julia> 2^4 16 Bitwise Operators Following table shows the bitwise operators that are supported on Julia’s primitive numeric types − Sl.No Expression Name Name 1 ∼x bitwise not 2 x & y bitwise and 3 x | y bitwise or 4 x ⊻ y bitwise xor (exclusive or) 5 x >>> y logical shift right 6 x >> y arithmetic shift right 7 x << y logical/arithmetic shift left Example Following example shows the use of bitwise operators − julia> ∼1009 -1010 julia> 12&23 4 julia> 12 & 23 4 julia> 12 | 23 31 julia> 12 ⊻ 23 27 julia> xor(12, 23) 27 julia> ∼UInt32(12) 0xfffffff3 julia> ∼UInt8(12) 0xf3 Updating Operators Each arithmetic as well as bitwise operator has an updating version which can be formed by placing an equal sign (=) immediately after the operator. This updating operator assigns the result of the operation back into its left operand. It means that a +=1 is equal to a = a+1. Following is the list of the updating versions of all the binary arithmetic and bitwise operators − += -= *= /= = ÷= %= ^= &= |= ⊻= >>>= >>= <<= Example Following example shows the use of updating operators − julia> A = 100 100 julia> A +=100 200 julia> A 200 Vectorized “dot” Operators For each binary operation like ^, there is a corresponding “dot”(.) operation which is used on the entire array, one by one. For instance, if you would try to perform [1, 2, 3] ^ 2, then it is not defined and not possible to square an array. On the other hand, [1, 2, 3] .^ 2 is defined as computing the vectorized result. In the same sense, this vectorized “dot” operator can also be used with other binary operators. Example Following example shows the use of “dot” operator − julia> [1, 2, 3].^2 3-element Array{Int64,1}: 1 4 9 Numeric Comparisons Operators Following table shows the numeric comparison operators that are supported on Julia’s primitive numeric types − Sl.No Operator Name 1 == Equality 2 !=,≠ inequality 3 < less than 4 <=, ≤ less than or equal to 5 > greater than 6 >=, ≥ greater than or equal to Example Following example shows the use of numeric comparison operators − julia> 100 == 100 true julia> 100 == 101 false julia> 100 != 101 true julia> 100 == 100.0 true julia> 100 < 500 true julia> 100 > 500 false julia> 100 >= 100.0 true julia> -100 <= 100 true julia> -100 <= -100 true julia> -100 <= -500 false julia> 100 < -10.0 false Chaining Comparisons In Julia, the comparisons can be arbitrarily chained. In case of numerical code, the chaining comparisons are quite convenient. The && operator for scalar comparisons and & operator for elementwise comparison allows chained comparisons to work fine on arrays. Example Following example shows the use of chained comparison − julia> 100 < 200 <= 200 < 300 == 300 > 200 >= 100 == 100 < 300 != 500 true In the following example, let us check out the evaluation behavior of chained comparisons − julia> M(a) = (println(a); a) M (generic function with 1 method) julia> M(1) < M(2) <= M(3) 2 1 3 true julia> M(1) > M(2) <= M(3) 2 1 false Operator Precedence & Associativity From highest precedence to lowest, the following table shows the order and associativity of operations applied by Julia − Category Operators Associativity Syntax followed by :: Left Exponentiation ^ Right Unary + – √ Right Bitshifts << >> >>> Left Fractions // Left Multiplication
Working with Graphics
Julia Programming – Working with Graphics ”; Previous Next This chapter discusses how to plot, visualize and perform other (graphic) operations on data using various tools in Julia. Text Plotting with Cairo Cairo, a 2D graphics library, implements a device context to the display system. It works with Linux, Windows, OS X and can create disk files in PDF, PostScript, and SVG formats also. The Julia file of Cairo i.e. Cairo.jl is authentic to its C API. Example The following is an example to draw a line − First, we will create a cr context. julia> using Cairo julia> img = CairoRGBSurface(512, 128); julia> img = CairoRGBSurface(512, 128); julia> cr = CairoContext(img); julia> save(cr); Now, we will add a rectangle − julia> set_source_rgb(cr, 0.5, 0.5, 0.5); julia> rectangle(cr, 0.0, 0.0, 512.0, 128.0); julia> fill(cr); julia> restore(cr); julia> save(cr); Now, we will define the points and draw a line through those points − julia> x0=61.2; y0=74.0; julia> x1=214.8; y1=125.4; julia> x2=317.2; y2=22.8; julia> x3=470.8; y3=74.0; julia> move_to(cr, x0, y0); julia> curve_to(cr, x1, y1, x2, y2, x3, y3); julia> set_line_width(cr, 10.0); julia> stroke_preserve(cr); julia> restore(cr); Finally, writing the resulting graphics to the disk − julia> move_to(cr, 12.0, 12.0); julia> set_source_rgb(cr, 0, 0, 0); julia> show_text(cr,”Line_Figure”) julia> write_to_png(c,”Line_Figure.png”); Output Text Plotting with Winston Winston is also a 2D graphics library. It resembles the built-in graphics available within MATLAB. Example julia> x = range(0, stop=3pi, length=100); julia> c = cos.(x); julia> s = sin.(x); julia> p = FramedPlot( title=”Winston Graphics!”, xlabel=”\Sigma x^2_i”, ylabel=”\Theta_i”) julia> add(p, FillBetween(x, c, x, s)) julia> add(p, Curve(x, c, color=”black”)) julia> add(p, Curve(x, s, color=”red”)) Output Data Visualization Data visualization may be defined as the presentation of data in a variety of graphical as well as pictorial formats such as pie and bar charts. Gadfly Gadfly is a powerful Julia package for data visualization and an implementation of the “grammar of graphics” style. It is based on the same principal as ggplot2 in R. For using it, we need to first add it with the help of Julia package manager. Example To use Gadfly, we first need to use RDatasets package so that we can get some datasets to work with. In this example, we will be using iris dataset − julia> using Gadfly julia> using RDatasets julia> iris = dataset(“datasets”, “iris”); julia> first(iris,10) 10×5 DataFrame │ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │ │ │ Float64 │ Float64 │ Float64 │ Float64 │ Cat… │ ├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤ │ 1 │ 5.1 │ 3.5 │ 1.4 │ 0.2 │ setosa │ │ 2 │ 4.9 │ 3.0 │ 1.4 │ 0.2 │ setosa │ │ 3 │ 4.7 │ 3.2 │ 1.3 │ 0.2 │ setosa │ │ 4 │ 4.6 │ 3.1 │ 1.5 │ 0.2 │ setosa │ │ 5 │ 5.0 │ 3.6 │ 1.4 │ 0.2 │ setosa │ │ 6 │ 5.4 │ 3.9 │ 1.7 │ 0.4 │ setosa │ │ 7 │ 4.6 │ 3.4 │ 1.4 │ 0.3 │ setosa │ │ 8 │ 5.0 │ 3.4 │ 1.5 │ 0.2 │ setosa │ │ 9 │ 4.4 │ 2.9 │ 1.4 │ 0.2 │ setosa │ │ 10 │ 4.9 │ 3.1 │ 1.5 │ 0.1 │ setosa │ Now let us plot a scatter plot. We will be using the variables namely SepalLength and SepalWidth. For this, we need to set the geometry element using Geom.point as follows − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point) Similarly we can add some more geometries like geom.line to produce more layers in the plot − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point, Geom.line) We can also set the color of keyword argument as follows − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, color = :Species, Geom.point) Compose Compose is a declarative vector graphics system. It is also written by Daniel Jones as a part of the Gadfly system. In Compose, the graphics are defined using a tree structure and the primitives can be classified as follows − Context − It represents an internal node. Form − It represents a leaf node which defines some geometry such as a circle or line. Property − It represents a leaf node that modifies how its parent’s subtree is drawn. For example, fill color and line width. Compose(x,y) − It returns a new tree rooted at x and with y attached as child. Example The below example will draw a simple image − julia> using Compose julia> composition = compose(compose(context(), rectangle()), fill(“tomato”)) julia> draw(SVG(“simple.svg”, 6cm, 6cm), composition) Now let us form more complex trees by grouping subtrees with brackets − julia> composition = compose(context(), (context(), circle(), fill(“bisque”)), (context(), rectangle(), fill(“tomato”))) julia> composition |> SVG(“simple2.svg”) Graphics Engines In this section, we shall discuss various graphic engines used in Julia. PyPlot PyPlot, arose from the previous development of the PyCall module, provides a Julia interface to the Matplotlib plotting library from Python. It uses the PyCall package to call Matplotlib directly from Julia. To work with PytPlot, we need to do the following setup − julia> using Pkg julia> pkg”up; add PyPlot Conda” julia> using Conda julia> Conda.add(“matplotlib”) Once you are done with this setup, you can simply import PyPlot by using PyPlot command. It will let you make calling functions in matplotlib.pyplot. Example This example, from PyPlot documentation, will create a sinusoidally modulated sinusoid − julia> using PyPlot julia> x = range(0; stop=2*pi, length=500); julia> y = sin.(3 * x + 4 * cos.(2 * x)); julia> plot(x, y, color=”blue”, linewidth=1.0, linestyle=”–“) 1-element Array{PyCall.PyObject,1}: PyObject <matplotlib.lines.Line2D object at 0x00000000323405E0> julia> title(“A sinusoidally modulated sinusoid”) PyObject Text(0.5, 1.0, ”A sinusoidally modulated sinusoid”) The PyPlot package can also be used for 3d plotting and for this it can import functions from Matplotlib’s mplot3d toolkit. We can create 3d plots directly also by calling some corresponding methods such as bar3d, plot_surface, plot3d, etc., of Axes3d. For example, we can plot a random surface
Rational and Complex Numbers ”; Previous Next In this chapter, we shall discuss rational and complex numbers. Rational Numbers Julia represents exact ratios of integers with the help of rational number type. Let us understand about rational numbers in Julia in further sections − Constructing rational numbers In Julia REPL, the rational numbers are constructed by using the operator //. Below given is the example for the same − julia> 4//5 4//5 You can also extract the standardized numerator and denominator as follows − julia> numerator(8//9) 8 julia> denominator(8//9) 9 Converting to floating-point numbers It is very easy to convert the rational numbers to floating-point numbers. Check out the following example − julia> float(2//3) 0.6666666666666666 Converting rational to floating-point numbers does not loose the following identity for any integral values of A and B. For example: julia> A = 20; B = 30; julia> isequal(float(A//B), A/B) true Complex Numbers As we know that the global constant im, which represents the principal square root of -1, is bound to the complex number. This binding in Julia suffice to provide convenient syntax for complex numbers because Julia allows numeric literals to be contrasted with identifiers as coefficients. julia> 2+3im 2 + 3im Performing Standard arithmetic operations We can perform all the standard arithmetic operations on complex numbers. The example are given below − julia> (2 + 3im)*(1 – 2im) 8 – 1im julia> (2 + 3im)/(1 – 2im) -0.8 + 1.4im julia> (2 + 3im)+(1 – 2im) 3 + 1im julia> (2 + 3im)-(1 – 2im) 1 + 5im julia> (2 + 3im)^2 -5 + 12im julia> (2 + 3im)^2.6 -23.375430842463754 + 15.527174176755075im julia> 2(2 + 3im) 4 + 6im julia> 2(2 + 3im)^-2.0 -0.059171597633136105 – 0.14201183431952663im Combining different operands The promotion mechanism in Julia ensures that combining different kind of operators works fine on complex numbers. Let us understand it with the help of the following example − julia> 2(2 + 3im) 4 + 6im julia> (2 + 3im)-1 1 + 3im julia> (2 + 3im)+0.7 2.7 + 3.0im julia> (2 + 3im)-0.7im 2.0 + 2.3im julia> 0.89(2 + 3im) 1.78 + 2.67im julia> (2 + 3im)/2 1.0 + 1.5im julia> (2 + 3im)/(1-3im) -0.7000000000000001 + 0.8999999999999999im julia> 3im^3 0 – 3im julia> 1+2/5im 1.0 – 0.4im Functions to manipulate complex values In Julia, we can also manipulate the values of complex numbers with the help of standard functions. Below are given some example for the same − julia> real(4+7im) #real part of complex number 4 julia> imag(4+7im) #imaginary part of complex number 7 julia> conj(4+7im) # conjugate of complex number 4 – 7im julia> abs(4+7im) # absolute value of complex number 8.06225774829855 julia> abs2(4+7im) #squared absolute value 65 julia> angle(4+7im) #phase angle in radians 1.0516502125483738 Let us check out the use of Elementary Functions for complex numbers in the below example − julia> sqrt(7im) #square root of imaginary part 1.8708286933869707 + 1.8708286933869707im julia> sqrt(4+7im) #square root of complex number 2.455835677350843 + 1.4251767869809258im julia> cos(4+7im) #cosine of complex number -358.40393224005317 + 414.96701031076253im julia> exp(4+7im) #exponential of complex number 41.16166839296141 + 35.87025288661357im julia> sinh(4+7im) #Hyperbolic sine value of complex number 20.573930095756726 + 17.941143007955223im Print Page Previous Next Advertisements ”;
Julia – Databases
Julia Programming – Databases ”; Previous Next Following are the four mechanisms for interfacing with a particular database system − First method of accessing a database is by using the set of routines in an API (Application Program Interface). In this method, the DBMS will be bundled as a set of query and maintenance utilities. These utilities will communicate with the running database through a shared library which further will be exposed to the user as a set of routines in an API. Second method is via an intermediate abstract layer. This abstract layer will communicate with the database API via a driver. Some example of such drivers are ODBC, JDBC, and Database Interface (DBI). Third approach is to use Python module for a specific database system. PyCall package will be used to call routines in the Python module. It will also handle the interchange of datatypes between Python and Julia. The fourth method is sending messages to the database. RESTful is the most common messaging protocol. Julia Database APIs Julia provides several APIs to communicate with various database providers. MySQL MySQL.jl is the package to access MySQL from Julia programming language. Use the following code to install the master version of MySQL API − Pkg.clone(“https://github.com/JuliaComputing/MySQL.jl”) Example To access MySQL API, we need to first connect to the MySQL server which can be done with the help of following code −` using MySQL con = mysql_connect(HOST, USER, PASSWD, DBNAME) To work with database, use the following code snippet to create a table − command = “””CREATE TABLE Employee ( ID INT NOT NULL AUTO_INCREMENT, Name VARCHAR(255), Salary FLOAT, JoinDate DATE, LastLogin DATETIME, LunchTime TIME, PRIMARY KEY (ID) );””” response = mysql_query(con, command) if (response == 0) println(“Create table succeeded.”) else println(“Create table failed.”) end We can use the following command to obtain the SELECT query result as dataframe − command = “””SELECT * FROM Employee;””” dframe = execute_query(con, command) We can use the following command to obtain the SELECT query result as Julia Array − command = “””SELECT * FROM Employee;””” retarr = mysql_execute_query(con, command, opformat=MYSQL_ARRAY) We can use the following command to obtain the SELECT query result as Julia Array with each row as a tuple − command = “””SELECT * FROM Employee;””” retarr = mysql_execute_query(con, command, opformat=MYSQL_TUPLES) We can execute a multi query as follows − command = “””INSERT INTO Employee (Name) VALUES (””); UPDATE Employee SET LunchTime = ”15:00:00” WHERE LENGTH(Name) > 5;””” data = mysql_execute_query(con, command) We can get dataframes by using prepared statements as follows − command = “””SELECT * FROM Employee;””” stmt = mysql_stmt_init(con) if (stmt == C_NULL) error(“Error in initialization of statement.”) end response = mysql_stmt_prepare(stmt, command) mysql_display_error(con, response != 0, “Error occured while preparing statement for query “$command””) dframe = mysql_stmt_result_to_dataframe(stmt) mysql_stmt_close(stmt) Use the following command to close the connection − mysql_disconnect(con) JDBC JDBC.jl is Julia interface to Java database drivers. The package JDBC.jl enables us the use of Java JDBC drivers to access databases from within Julia programming language. To start working with it, we need to first add the database driver jar file to the classpath and then initialize the JVM as follows − using JDBC JavaCall.addClassPath(“path of .jar file”) # add the path of your .jar file JDBC.init() Example The JDBC API in Julia is similar to Java JDBC driver. To connect with a database, we need to follow similar steps as shown below − conn = DriverManager.getConnection(“jdbc:gl:test/juliatest”) stmt = createStatement(conn) rs = executeQuery(stmt, “select * from mytable”) for r in rs println(getInt(r, 1), getString(r,”NAME”)) end If you want to get each row as a Julia tuple, use JDBCRowIterator to iterate over the result set. Note that if the values are declared to be nullable in the database, they will be of nullable in tuples also. for r in JDBCRowIterator(rs) println(r) end Updating the table Use PrepareStatement to do insert and update. It has setter functions defined for different types corresponding to the getter functions − ppstmt = prepareStatement(conn, “insert into mytable values (?, ?)”) setInt(ppstmt, 1,10) setString(ppstmt, 2,”TEN”) executeUpdate(ppstmt) Running stored procedures Use CallableStatement to run the stored procedure − cstmt = JDBC.prepareCall(conn, “CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)”) setString(cstmt, 1, “gl.locks.deadlockTimeout”) setString(cstmt, 2, “10”) execute(cstmt) Metadata In order to get an array of (column_name, column_type) tuples, we need to Pass the JResultSet object from executeQuery to getTableMetaData as follows − conn = DriverManager.getConnection(“jdbc:gl:test/juliatest”) stmt = createStatement(conn) rs = executeQuery(stmt, “select * from mytable”) metadata = getTableMetaData(rs) Use the following command to close the connection − close(conn) Executing a query For executing a query, we need a cursor first. Once obtained a cursor you can run execute! command on the cursor as follows − csr = cursor(conn) execute!(csr, “insert into ptable (pvalue) values (3.14);”) execute!(csr, “select * from gltable;”) Iterating over the rows We need to call rows on the cursor to iterate over the rows − rs = rows(csr) for row in rs end Use the following command to close the cursor call − close(csr) ODBC ODBC.jl is a package which provides us a Julia ODBC API interface. It is implemented by various ODBC driver managers. We can install it as follows − julia> Pkg.add(“ODBC”) Installing ODBC Driver Use the command below to install an ODBC driver − ODBC.adddriver(“name of driver”, “full, absolute path to driver shared library”; kw…) We need to pass − The name of the driver The full and absolute path to the driver shared library And any additional keyword arguments which will be included as KEY=VALUE pairs in the .ini config files. Enabling Connections After installing the drivers, we can do the following for enabling connections − Setup a DSN, via ODBC.adddsn(“dsn name”, “driver name”; kw…) Connecting directly by using a full connection string like ODBC.Connection(connection_string) Executing Queries
Working with Datasets
Julia Programming – Working with Datasets ”; Previous Next In this chapter, we shall discuss in detail about datasets. CSV files As we know that CSV (Comma Separated Value) file is a plain text file which uses commas to separate fields and values of those fields. The extension of these files is .CSV. We have various methods provided by Julia programming language to perform operations on CSV files. Import a .CSV file in Julia To import a .CSV file, we need to install CSV package. Use the following command to do so − using pkg pkg.add(“CSV”) Reading data To read data from a CSV file in Julia we need to use read() method from CSV package as follows − julia> using CSV julia> CSV.read(“C://Users//Leekha//Desktop//Iris.csv”) 150×6 DataFrame │ Row │ Id │ SepalLengthCm │ SepalWidthCm │ PetalLengthCm │ PetalWidthCm │ Species │ │ │ Int64 │ Float64 │ Float64 │ Float64 │ Float64 │ String │ ├─────┼───────┼───────────────┼──────────────┼───────────────┼──────────────┼─────────——-┤ │ 1 │ 1 │ 5.1 │ 3.5 │ 1.4 │ 0.2 │ Iris-setosa │ │ 2 │ 2 │ 4.9 │ 3.0 │ 1.4 │ 0.2 │ Iris-setosa │ │ 3 │ 3 │ 4.7 │ 3.2 │ 1.3 │ 0.2 │ Iris-setosa │ │ 4 │ 4 │ 4.6 │ 3.1 │ 1.5 │ 0.2 │ Iris-setosa │ │ 5 │ 5 │ 5.0 │ 3.6 │ 1.4 │ 0.2 │ Iris-setosa │ │ 6 │ 6 │ 5.4 │ 3.9 │ 1.7 │ 0.4 │ Iris-setosa │ │ 7 │ 7 │ 4.6 │ 3.4 │ 1.4 │ 0.3 │ Iris-setosa │ │ 8 │ 8 │ 5.0 │ 3.4 │ 1.5 │ 0.2 │ Iris-setosa │ │ 9 │ 9 │ 4.4 │ 2.9 │ 1.4 │ 0.2 │ Iris-setosa │ │ 10 │ 10 │ 4.9 │ 3.1 │ 1.5 │ 0.1 │ Iris-setosa │ ⋮ │ 140 │ 140 │ 6.9 │ 3.1 │ 5.4 │ 2.1 │ Iris-virginica │ │ 141 │ 141 │ 6.7 │ 3.1 │ 5.6 │ 2.4 │ Iris-virginica │ │ 142 │ 142 │ 6.9 │ 3.1 │ 5.1 │ 2.3 │ Iris-virginica │ │ 143 │ 143 │ 5.8 │ 2.7 │ 5.1 │ 1.9 │ Iris-virginica │ │ 144 │ 144 │ 6.8 │ 3.2 │ 5.9 │ 2.3 │ Iris-virginica │ │ 145 │ 145 │ 6.7 │ 3.3 │ 5.7 │ 2.5 │ Iris-virginica │ │ 146 │ 146 │ 6.7 │ 3.0 │ 5.2 │ 2.3 │ Iris-virginica │ │ 147 │ 147 │ 6.3 │ 2.5 │ 5.0 │ 1.9 │ Iris-virginica │ │ 148 │ 148 │ 6.5 │ 3.0 │ 5.2 │ 2.0 │ Iris-virginica │ │ 149 │ 149 │ 6.2 │ 3.4 │ 5.4 │ 2.3 │ Iris-virginica │ │ 150 │ 150 │ 5.9 │ 3.0 │ 5.1 │ 1.8 │ Iris-virginica │ Creating new CSV file To create new CSV file, we need to use touch()command from CSV package. We also need to use DataFrames package to write the newly created content to new CSV file − julia> using DataFrames julia> using CSV julia> touch(“1234.csv”) ”1234.csv” julia> new = open(“1234.csv”, “w”) IOStream(<file 1234.csv>) julia> new_data = DataFrame(Name = [“Gaurav”, “Rahul”, “Aarav”, “Raman”, “Ravinder”], RollNo = [1, 2, 3, 4, 5], Marks = [54, 67, 90, 23, 95]) 5×3 DataFrame │ Row │ Name │ RollNo │ Marks │ │ │ String │ Int64 │ Int64 │ ├─────┼──────────┼────────┼───────┤ │ 1 │ Gaurav │ 1 │ 54 │ │ 2 │ Rahul │ 2 │ 67 │ │ 3 │ Aarav │ 3 │ 90 │ │ 4 │ Raman │ 4 │ 23 │ │ 5 │ Ravinder │ 5 │ 95 │ julia> CSV.write(“1234.csv”, new_data) ”1234.csv” julia> CSV.read(“1234.csv”) 5×3 DataFrame │ Row │ Name │ RollNo │ Marks │ │ │ String │ Int64 │ Int64 │ ├─────┼──────────┼────────┼───────┤ │ 1 │ Gaurav │ 1 │ 54 │ │ 2 │ Rahul │ 2 │ 67 │ │ 3 │ Aarav │ 3 │ 90 │ │ 4 │ Raman │ 4 │ 23 │ │ 5 │ Ravinder │ 5 │ 95 │ HDF5 The full form of HDF5 is Hierarchical Data Format v5. Following are some of its properties − A “group” is similar to a directory, a “dataset” is like a file. To associate metadata with a particular group, it uses attributes. It uses ASCII names for different objects. Language wrappers are often known as “low level” or “high level”. Opening HDF5 files HDF5 files can be opened with h5open command as follows − fid = h5open(filename, mode) Following table describes the mode − Sl.No Mode & Meaning 1 “r” read-only 2 “r+” read-write − It will preserve any existing contents. 3 “cw” read-write − It will create file if not existing. It will also preserve existing contents. 4 “w” read-write − It will destroy any existing contents. The above command will produce an object of type HDF5File and a subtype of the abstract type DataFile. Closing HDF5 files Once finished with a file, we should close it as follows − close(fid) It will also close all the objects in the file. Opening HDF5 objects Suppose if we have a file object named fid and it has a group called object1, it can be opened as follows − Obj1 = fid[“object1”] Closing HDF5 objects close(obj1) Reading data A group “g” containing a dataset with path “dtset” and we have opened dataset as dset1 = g[dtset]. We can read the information in following ways − ABC = read(dset1) ABC = read(g, “dtset”) Asub = dset1[2:3, 1:3] Writing data We can create the dataset as follows − g[“dset1”] = rand(3,5) write(g, “dset1”, rand(3,5)) XML files Here we will be discussing about LightXML.jl package which is a light-weight Julia wrapper for libxml2. It provides the following functionalities − Parsing an XML file
Julia – Overview
Julia – Overview ”; Previous Next What is Julia Programming Language? One of the facts about scientific programming is that it requires high performance flexible dynamic programming language. Unfortunately, to a great extent, the domain experts have moved to slower dynamic programming languages. There can be many good reasons for using such dynamic programming languages and, in fact, their use cannot be diminished as well. On the flip side, what can we expect from modern language design and compiler techniques? Some of the expectations are as follows − It should eradicate the performance trade-off. It should provide the domain experts a single environment that is productive enough for prototyping. It should provide the domain experts a single environment that is efficient enough for deploying performance-intensive applications. The Julia programming language fulfills these expectations. It is a general purpose high-performance flexible programming language which can be used to write any application. It is well-suited for scientific and numerical computing. History of Julia Let us see the history of Julia programming language in the following points − Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman has started to work on Julia in 2009. The developer’s team of above four has launched a website on 14th February 2012. This website had a blog post primarily explaining the mission of Julia programming language. Later in April 2012, Stefan Karpinski, in an interview with a magazine named InfoWorld, gave the name “Julia” for their programming language. In 2014, the annual academic conference named ‘The JuliaCon’ for Julia; users and developers has been started and since then it was regularly held every year. In August 2014, Julia Version 0.3 was released for use. In October 2015, Julia Version 0.4 was released for use. In October 2016, Julia Version 0.5 was released for use. In June 2017 Julia Version 0.6 was released for use. Julia Version 0.7 and Version 1.0 were both released on the same date 8th August 2018. Among them Julia version 0.7 was particularly useful for testing packages as well as for the users who wants to upgrade to version 1.0. Julia versions 1.0.x are the oldest versions which are still supported. In January 2019, Julia Version 1.1 was released for use. In August 2019, Julia Version 1.2 was released for use. In November 2019, Julia Version 1.3 was released for use. In March 2020, Julia Version 1.4 was released for use. In August 2020, Julia Version 1.5 was released for use. Features of Julia Following are some of the features and capabilities offered by Julia − Julia provides us unobtrusive yet a powerful and dynamic type system. With the help of multiple dispatch, the user can define function behavior across many combinations of arguments. It has powerful shell that makes Julia able to manage other processes easily. The user can cam call C function without any wrappers or any special APIs. Julia provides an efficient support for Unicode. It also provides its users the Lisp-like macros as well as other metaprogramming processes. It provides lightweight green threading, i.e., coroutines. It is well-suited for parallelism and distributed computation. The coding done in Julia is fast because there is no need of vectorization of code for performance. It can efficiently interface with other programming languages such as Python, R, and Java. For example, it can interface with Python using PyCall, with R using RCall, and with Java using JavaCall. The Scope of Julia Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman, the core designers and developers of Julia, have made it clear that Julia was explicitly designed to bridge the following gap in the existing software toolset in the technical computing discipline − Prototyping − Prototyping is one such problem in technical computing discipline that needs a high-level and flexible programming language so that the developer should not worry about the low-level details of computation and the programming language itself. Performance − The actual computation needs maximum performance. The production version of a programming language should be often written in “Fortran” or “C” programming language. Speed − Another important issue in technical domain is the speed. Before Julia, the programmers need to have mastery on both high-level programming (for writing code in Matlab, R, or, Python for prototyping) and low-level programming (writing performance-sensitive parts of programs, to speed up the actual computation, in statistically complied languages such as C or Fortran). Julia programming language gives the practitioners a possibility of writing high-performance programs that uses computer resources such as CPU and memory as effectively as C or Fortran. In this sense, Julia reduces the need for a low-level programming language. The recent advances in Julia, LLVM JIT (Low Level Virtual Machine Just in Time) compiler technology proves that working in one environment that has expressive capabilities and pure speed is possible. Comparison with other languages One of the goals of data scientists is to achieve expressive capabilities and pure speed that avoids the need to go for ‘C’ programming language. Julia provides the programmers a new era of technical computing where they can develop libraries in a high-level programming language. Following is the detailed comparison of Julia with the most used programming languages — Matlab, R, and Python − MATLAB − The syntax of Julia is similar to MATLAB, however it is a much general purpose language when compared to MATLAB. Although most of the names of functions in Julia resemble OCTAVE (the open source version of MATLAB), the computations are extremely different. In the field of linear algebra, Julia has equally powerful capabilities as that of MATLAB, but it will not give its users the same license fee issues. In comparison to OCTAVE,
Julia – Metaprogramming
Julia Programming – Metaprogramming ”; Previous Next Metaprogramming may be defined as the programming in which we write Julia code to process and modify Julia code. With the help of Julia metaprogramming tools, one can write Julia programming code that modifies other parts of the source code file. These tools can even control when the modified code runs. Following are the execution stages of raw source code − Stage 1 − Raw Julia code is parsed In this stage the raw Julia code is converted into a form suitable for evaluation. The output of this stage is AST i.e. Abstract Syntax Tree. AST is a structure which contains all the code in an easy to manipulate format. Stage 2 − Parsed Julia code is executed In this stage, the evaluated Julia code is executed. When we type code in REPL and press Return the two stages happens but they happen so quickly that we don’t even notice. But with metaprogramming tools we can access the Julia code between two stages, i.e. after code parsed but before its evaluation. Quoted expressions As we discussed, with metaprogramming we can access the Julia code between two stages. For this, Julia has ‘:’ colon prefix operator. With the help of colon operator, Julia store an unevaluated but parsed expression. Example julia> ABC = 100 100 julia> :ABC :ABC Here, − ABC is quoted or unevaluated symbol for Julia i.e. ‘ABC ‘ is an unevaluated symbol rather than having the value 100. We can quote the whole expressions as below − julia> :(100-50) :(100 – 50) Alternatively, we can also use quote…end keywords to enclose and quote an expression as follows − julia> quote 100 – 50 end quote #= REPL[43]:2 =# 100 – 50 end Check this also: julia> expression = quote for x = 1:5 println(x) end end quote #= REPL[46]:2 =# for x = 1:5 #= REPL[46]:3 =# println(x) end end julia> typeof(expression) Expr It shows that expression object is parsed, primed and ready to use. Evaluated expressions Once you parsed the expression, there is a way to evaluate the expression also. We can use the function eval() for this purpose as follows − julia> eval(:ABC) 100 julia> eval(:(100-50)) 50 julia> eval(expression) 1 2 3 4 5 In the example, we have evaluated the expressions parsed in above section. The Abstract Syntax Tree (AST) As discussed above, Abstract Syntax Tree (AST) is a structure which contains all the code in an easy to manipulate format. It is the output of stage1. It allows us to easily process and modify the Julia code. We can visualize the hierarchical nature of an expression with the help of dump() function. Example julia> dump(:(1 * cos(pi/2))) Expr head: Symbol call args: Array{Any}((3,)) 1: Symbol * 2: Int64 1 3: Expr head: Symbol call args: Array{Any}((2,)) 1: Symbol cos 2: Expr head: Symbol call args: Array{Any}((3,)) 1: Symbol / 2: Symbol pi 3: Int64 2 Expression interpolation Any Julia code which has string or expression is usually unevaluated but with the help of dollar ($) sign (string interpolation operator), we can evaluate some of the code. The Julia code will be evaluated and inserts the resulting value into the string when the string interpolation operator is used inside a string. Example julia> “the cosine of 1 is $(cos(1))” ”the cosine of 1 is 0.5403023058681398″ Similarly, we can use this string interpolation operator to include the results of executing Julia code interpolated into unevaluated expression − julia> quote ABC = $(cos(1) + tan(1)); end quote #= REPL[54]:1 =# ABC = 2.097710030523042 end Macros We are now aware of creating and handling unevaluated expressions. In this section, we will understand how we can modify them. Julia provides macro that accepts an unevaluated expression as input and generates a new output expression. If we talk about its working, Julia first parses and evaluates the macro, and then the processed code produced by macro will be evaluated like an ordinary expression. The syntax of defining a macro is very similar to that of a function. Following is the definition of macro that will print out the contents of the things we pass to it − julia> macro x(n) if typeof(n) == Expr println(n.args) end return n end @x (macro with 1 method) We can run the macros by preceding the name of the macro with the @ prefix − julia> @x 500 500 julia> @x “Tutorialspoint.com” ”Tutorialspoint.com” eval() and @eval Julia has eval() function and a macro called @eval. Let us see example to know their differences − julia> ABC = :(100 + 50) :(100 + 50) julia> eval(ABC) 150 The above output shows that the eval() function expands the expression and evaluates it. julia> @eval ABC :(100 + 50) julia> @eval $(ABC) 150 It can also be treated as follows − julia> @eval $(ABC) == eval(ABC) true Expanding Macros The macroexpand() function returns the expanded format (used by the Julia compiler before it is finally executed) of the specified macro. Example julia> macroexpand(Main, quote @p 1 + 4 – 6 * 7 / 8 % 9 end) Any[:-, :(1 + 4), :(((6 * 7) / 8) % 9)] quote #= REPL[69]:1 =# (1 + 4) – ((6 * 7) / 8) % 9 end Print Page Previous Next Advertisements ”;
Julia – Functions
Julia – Functions ”; Previous Next Function, the building blocks of Julia, is a collected group of instructions that maps a tuple of argument values to a return value. It acts as the subroutines, procedures, blocks, and other similar structures concepts found in other programming languages. Defining Functions There are following three ways in which we can define functions − When there is a single expression in a function, you can define it by writing the name of the function and any arguments in parentheses on the left side and write an expression on the right side of an equal sign. Example julia> f(a) = a * a f (generic function with 1 method) julia> f(5) 25 julia> func(x, y) = sqrt(x^2 + y^2) func (generic function with 1 method) julia> func(5, 4) 6.4031242374328485 If there are multiple expressions in a function, you can define it as shown below − function functionname(args) expression expression expression … expression end Example julia> function bills(money) if money < 0 return false else return true end end bills (generic function with 1 method) julia> bills(50) true julia> bills(-50) false If a function returns more than one value, we need to use tuples. Example julia> function mul(x,y) x+y, x*y end mul (generic function with 1 method) julia> mul(5, 10) (15, 50) Optional Arguments It is often possible to define functions with optional arguments i.e. default sensible values for functions arguments so that the function can use that value if specific values are not provided. For example − julia> function pos(ax, by, cz=0) println(“$ax, $by, $cz”) end pos (generic function with 2 methods) julia> pos(10, 30) 10, 30, 0 julia> pos(10, 30, 50) 10, 30, 50 You can check in the above output that when we call this function without supplying third value, the variable cz defaults to 0. Keyword Arguments Some functions which we define need a large number of arguments but calling such functions can be difficult because we may forget the order in which we have to supply the arguments. For example, check the below function − function foo(a, b, c, d, e, f) … end Now, we may forget the order of arguments and the following may happen − foo(“25”, -5.6987, “hello”, 56, good, ‘ABC’) or foo(“hello”, 56, “25”, -5.6987, ‘ABC’, good) Julia provides us a way to avoid this problem. We can use keywords to label arguments. We need to use a semicolon after the function’s unlabelled arguments and follow it with one or more keyword-value pair as follows − julia> function foo(a, b ; c = 10, d = “hi”) println(“a is $a”) println(“b is $b”) return “c => $c, d => $d” end foo (generic function with 1 method) julia> foo(100,20) a is 100 b is 20 ”c => 10, d => hi” julia> foo(“Hello”, “Tutorialspoint”, c=pi, d=22//7) a is Hello b is Tutorialspoint ”c => π, d => 22//7″ It is not necessary to define the keyword argument at the end or in the matching place, it can be written anywhere in the argument list. Following is an example − julia> foo(c=pi, d =22/7, “Hello”, “Tutorialspoint”) a is Hello b is Tutorialspoint ”c => π, d => 3.142857142857143″ Anonymous Functions It is waste of time thinking a cool name for your function. Use Anonymous functions i.e. functions with no name instead. In Julia, such functions can be used in number of places such as map() and in list comprehensions. The syntax of anonymous functions uses the symbol ->. You can check the below example − A -> A^3 + 3A – 3 The above function is an anonymous function that takes an argument A and returns A^3 + 3A – 3. It can be used with map() function whose first argument is a function and we can define an one-off function that exists just for one particular map() operation. The example is given below − julia> map(A -> A^3 + 3A – 3, [10,3,-2]) 3-element Array{Int64,1}: 1027 33 -17 Once the map() function finishes, the function and argument both will disappear − julia> A ERROR: UndefVarError: A not defined Recursive Functions In Julia, the functions can be nested. It is demonstrated in the example given below − julia> function add(x) Y = x * 2 function add1(Y) Y += 1 end add1(Y) end add (generic function with 1 method) julia> d = 10 10 julia> add(d) 21 In the same way, a function in Julia can be recursive also. It means the function can call itself. Before getting into details, we first need to test a condition in code which can be done with the help of ternary operator “?”. It takes the form expr ? a : b. It is called ternary because it takes three arguments. Here the expr is a condition, if it is true then a will be evaluated otherwise b. Let us use this in the following recursive definition − julia> sum(x) = x > 1 ? sum(x-1) + x : x sum (generic function with 1 method) The above statement calculates the sum of all the integers up to and including a certain number. But in this recursion ends because there is a base case, i.e., when x is 1, this value is returned. The most famous example of recursion is to calculate the nth Fibonacci number which is defined as the sum of two previous Fibonacci numbers. Let us understand it with the below given example − julia> fib(x) = x < 2 ? x : fib(x-1) + fib(x-2) fib (generic function with 1 method) Therefore while using recursion, we need to be careful to define a base case to stop calculation. Map Map may be defined as a function that takes the following form − map(func, coll) Here, func is a function applied successively to each element of collection coll. Map generally contains the anonymous function and returns a new collection. The example is given below − julia> map(A ->