## Julia Community π£

Vinod V

Posted on • Updated on

# 10 Julia Recipes You Can't Miss

a.Accept arbitray number of function arguments

``````function sum1(a, remaining...)
sm = a + sum(remaining)
println(sm)
end

sum1(1, 2, 3, 4,5)
sum1(1)
sum1(1,2,3)
``````

b.You can search and replace a simple text pattern in a string using the replace() method.

``````stri = "I scream, you scream, we all scream for ice cream."
stri = replace(stri, "scream" => "cry")
println(stri)
stri = "I scream, you scream, we all scream for ice cream."
replace(stri, "scream"=>uppercase) #replace scream by SCREAM
``````

c. Filtering a list based on some condition

``````temp = [56, 49, 50, 55, 53, 52, 60, 60, 42, 54]

# Only the elements that are greater than 50
filtered = [item for item in temp if item > 50]
print(filtered)

filtered = filter(>(50), temp)

filtered = filter(temp) do x
x > 50
end
``````

d.Unpack tuple to a list of variables

``````temp1 = (45, 51, 43, 49, 47)
a, b, c, d, e = temp1
print(a)
print(d)

stri = "Money"
c1, c2, c3, c4, c5 = stri

t = (a=1, b="hello", c = 3.14) #named tuple
(; a, c) = t; @show a; @show c; #a = 1,c = 3.14,b undefined
``````

e.Dictionary comprehension in Julia

``````marks = Dict("Ram" => 60, "Shyam" => 33, "Manik" => 64,"Mani" => 76, "Hema" => 84)

more_than_55 = Dict(key => value for (key, value) in marks if value > 60)
println(more_than_55)

names = Set(["Ram", "Hema", "Mani","Manik"])
selected = Dict(key => value for (key, value) in marks if key in names)
println(selected)
``````

f.Iterating in Reverse in Julia

``````for i in reverse(1:5)
print(i)
end

r = reverse("Julia")
"ailuJ"

for i in 1:length(r)
print(r[reverseind("Julia", i)])
end
``````

``````str = "Julia's syntax is good"
``````

h.Return multiple values from a function

``````function retMultipleValues()
v1,v2 = "India","Iran"
return v1,v2
end

countries = retMultipleValues()
println(countries)
``````

i. Creating and Writing to a Text File in Julia

``````fid = open("abc.txt", "x") #"x" flag ensures that the file is created only if it does not already exist.
write(fid, "Hello Julia")
close(fid)

open("def.txt", "w") do fid #no need for close statement
write(fid, "Hey")
end

#Read a text file line by line
for line in eachline("my_file.txt")
print(line)
end

#most compact
foreach(println,eachline("my_file.txt"))

``````

j. Parse date string to DateTime object

``````using Dates

dstr = "2023-07-03"
println(typeof(dstr))

date_time = DateTime(dstr, "yyyy-mm-dd")
println(date_time)
println(typeof(date_time))
``````

New trick suggested by reviewers:
k. Make a 10-element vector of random named tuples

``````points = [(x=rand(), y=rand()) for i in 1:10]
distances = [sqrt(p.x^2 + p.y^2) for p in points if p.x > p.y]
#distances = [hypot(p.x , p.y) for p in points if p.x > p.y]
``````

l. Unpacking of tuples of varying sizes (Julia version 1.9)

``````julia> a, b..., c = (1, 2, 3, 4)
(1, 2, 3, 4)

julia> a
1

julia> b
(2, 3)

julia> c
4

``````

m. Convert a number array to string

``````julia> r = join([1,2,3.1], ", ")
"1.0, 2.0, 3.1"
``````

n. Round a float to integer

``````julia> round(Int, 12.5) == Int(trunc(12.5))
true
``````

o. To parse a binary string to integer

``````parse(Int, "1011", base=2)
``````

p. To create a random binary string

`````` join(rand(['1','0'],10))
``````

q. Convert a `1 x n` matrix (row matrix) to a vector

``````B = [1 2 3 4]
1Γ4 Matrix{Int64}:
1  2  3  4
julia> dropdims(B,dims=1)
4-element Vector{Int64}:
1
2
3
4
``````

r. Convert a row vector to a column vector

``````B = [1 2 3 4]
1Γ4 Matrix{Int64}:
1  2  3  4
julia> permutedims(B)
4Γ1 Matrix{Int64}:
1
2
3
4
``````

s. Check occurrence of a number in a vector

``````a = [1,2,3]
in(1,a) # true
``````

t. The command `splice!` can be used to remove elements from an array by index

``````a = [1,2,3]
splice!(a,2)
a
[1,3]
``````

u. Get all the permutations with replacement (Cartesian product)

``````colors = ['R','G']
n = 3
vec(Iterators.product(fill(colors, n)...) |> collect)
8-element Vector{Tuple{Char, Char, Char}}:
('R', 'R', 'R')
('G', 'R', 'R')
('R', 'G', 'R')
('G', 'G', 'R')
('R', 'R', 'G')
('G', 'R', 'G')
('R', 'G', 'G')
('G', 'G', 'G')
``````

v. Raw string in julia

``````x = raw"C:/temp"
``````

w. Ternary operator with short circuited `&&`

``````x = 3 > 2 && 7 #x = 7
x = 2 > 3 && 7 #x = false
``````

x. List all the files in a foler

``````readdir(raw"C:\temp")
``````

y. Walk through the directory including subfolders

``````for (root,fold,files) in walkdir(raw"C:\temp")
for f in fl
println(joinpath(d,f))  #print all full file paths (python os.walk)
end
end
``````

z. Pretty print a matrix

``````julia> using DelimitedFiles

julia> a = rand(2,3);

julia>  writedlm(stdout, a)
0.29272827910923105     0.7551746399784662      0.22809145708060086
0.9698016822675571      0.7551356902700419      0.740811475230424
``````

aa. To get the indices of elements satisfying certain condition

`````` indices = findall(x -> x < 0, -4:10)
``````

ab. Import a package with a different name

``````import LinearAlgebra as la
``````

ac. Delete an element from a list

``````filter!(!=(1), [1,0,1,2,4])
``````

ad. Convert data type of any to float in matrix

``````A = Matrix{Any}(rand(2,2))
B = similar(A,Float64)
B .= A
``````

ae. Find the type of a Julia variable

``````a = 2
typeof(a)
a isa Int64
eltype(a)
``````

af. Convert IEEE 754 hexadecimal string to float

``````hexStr = Meta.parse(string("0b", bitstring(1.0f0)))
0x3f800000
reinterpret(Float32,hexStr)
1.0f0
``````

ag. To get the first half of the elements in a vector

``````x = rand(1024)
y =  x[1:endΓ·2] #y = x[1:512]
``````

ah. To restart the julia shell

``````run(`\$(Base.julia_cmd())`)
``````

Petr Krysl

Re (i): I personally like this pattern (takes care of the closing automatically):

``````open("def.txt", "w") do fid
write(fid, "Hey")
end
``````

Vinod V

Updated in the blog

Edward Carney

In item k., correct use of hypot, to make it equivalent to the sqrt() method, is hypot(p.x, p.y).

The one with a '+' returns the absolute value of the argument.

Vinod V

Corrected

hungpham3112

Can you check again the code format?

Vinod V • Edited

Done. I have replaced single tilde by three tildes followed by Julia. Now formatting is OK. Tilde code block is available as a default option in forem. It is not working properly.

Petr Krysl

Nice post!

I think what you mean is "backtick" (`). Tilda is ~.

Regards,

P

Vinod V

True

hungpham3112

Take a note at index of code block