Julia Community 🟣

Vinod V
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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

g.Padding Strings in Julia

str = "Julia's syntax is good"
println(lpad(str, 40, '*'))
******************Julia's syntax is good
println(rpad(str, 40, '*'))
Julia's syntax is good******************
Enter fullscreen mode Exit fullscreen mode

h.Return multiple values from a function

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

countries = retMultipleValues()
println(countries)
Enter fullscreen mode Exit fullscreen mode

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"))

readlines("my_file.txt")
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

m. Convert a number array to string

julia> r = join([1,2,3.1], ", ")
"1.0, 2.0, 3.1"
Enter fullscreen mode Exit fullscreen mode

n. Round a float to integer

julia> round(Int, 12.5) == Int(trunc(12.5))
true
Enter fullscreen mode Exit fullscreen mode

o. To parse a binary string to integer

parse(Int, "1011", base=2) 
Enter fullscreen mode Exit fullscreen mode

p. To create a random binary string

 join(rand(['1','0'],10))
Enter fullscreen mode Exit fullscreen mode

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
vec(B)
4-element Vector{Int64}:
 1
 2
 3
 4
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

s. Check occurrence of a number in a vector

a = [1,2,3]
in(1,a) # true
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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')                                
Enter fullscreen mode Exit fullscreen mode

v. Raw string in julia

x = raw"C:/temp"
Enter fullscreen mode Exit fullscreen mode

w. Ternary operator with short circuited &&

x = 3 > 2 && 7 #x = 7
x = 2 > 3 && 7 #x = false
Enter fullscreen mode Exit fullscreen mode

x. List all the files in a folder

readdir(raw"C:\temp") 
Enter fullscreen mode Exit fullscreen mode

y. Walk through the directory including subfolders

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

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
Enter fullscreen mode Exit fullscreen mode

aa. To get the indices of elements satisfying certain condition

 indices = findall(x -> x < 0, -4:10)
Enter fullscreen mode Exit fullscreen mode

ab. Import a package with a different name

import LinearAlgebra as la
Enter fullscreen mode Exit fullscreen mode

ac. Delete an element from a list

filter!(!=(1), [1,0,1,2,4])
Enter fullscreen mode Exit fullscreen mode

ad. Convert data type of any to float in matrix

A = Matrix{Any}(rand(2,2))
B = similar(A,Float64)
B .= A
Enter fullscreen mode Exit fullscreen mode

ae. Find the type of a Julia variable

a = 2
typeof(a)
a isa Int64
eltype(a)
Enter fullscreen mode Exit fullscreen mode

af. Convert IEEE 754 hexadecimal string to float

hexStr = Meta.parse(string("0b", bitstring(1.0f0)))
0x3f800000
reinterpret(Float32,hexStr)
1.0f0
reinterpret(UInt8,[1.0f0])
4-element reinterpret(UInt8, ::Vector{Float32}):
 0x00
 0x00
 0x80
 0x3f
Enter fullscreen mode Exit fullscreen mode

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

x = rand(1024)
y =  x[1:endΓ·2] #y = x[1:512]
Enter fullscreen mode Exit fullscreen mode

ah. To restart the julia shell

run(`$(Base.julia_cmd())`)
Enter fullscreen mode Exit fullscreen mode

Top comments (10)

Collapse
 
petrkryslucsd profile image
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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vinodv profile image
Vinod V

Updated in the blog

Collapse
 
edwcarney profile image
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.

Collapse
 
vinodv profile image
Vinod V

Corrected

Collapse
 
hungpham3112 profile image
hungpham3112

Can you check again the code format?

Collapse
 
vinodv profile image
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.

Collapse
 
petrkryslucsd profile image
Petr Krysl

Nice post!

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

Regards,

P

Thread Thread
 
vinodv profile image
Vinod V

True

Collapse
 
hungpham3112 profile image
hungpham3112

Take a note at index of code block

Thread Thread
 
vinodv profile image
Vinod V • Edited

I n the source I have numbered it properly. Is this a bug in forem software? I have changed indexing.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.