Julia Notes Day2 -- string and collections

·

6 min read

Char and String

A Char value represents a single character

c = 'x'
d = Int('x') # 120
e = Char(120)  # 'x'
f = '\u2200' # '∀': Unicode U+2200 (category Sm: Symbol, math)
g = 'A' + 1 # 'B'

String literals are delimited by double quotes or triple double quotes (not single quotes).

s = "\u2200 x \u2203 y" # "∀ x ∃ y"
s *= "世界" # "∀ x ∃ y世界"
length(s) # 9
sizeof(s) # 17
s[end] # '界': Unicode U+754C (category Lo: Letter, other)

findfirst('界',s) # 15

# Sequential iteration is implemented by the iterate function. 
# The general for loop:
for c in s
    print(c*' ')
end
# ∀   x   ∃   y 世 界

String literals are encoded using the UTF-8 encoding. UTF-8 is a variable-width encoding, meaning that not all characters are encoded in the same number of bytes ("code units"). In UTF-8, ASCII characters — i.e. those with code points less than 0x80 (128) – are encoded as they are in ASCII, using a single byte, while code points 0x80 and above are encoded using multiple bytes — up to four per character.

String indices in Julia refer to code units (= bytes for UTF-8), the fixed-width building blocks that are used to encode arbitrary characters (code points). This means that not every index into a String is necessarily a valid index for a character. If you index into a string at such an invalid byte index, an error is thrown

greet = "Hello"; whom = "world";

#Julia provides * for string concatenation
greet * ' ' * whom # "Hello world"

#interpolation into string literals using $
"$greet, $whom." # "Hello, world."

# triple-quoted strings are dedented to the level of the least-indented line.
str = """
           Hello,
           world.
         """
# "  Hello,\n  world.\n"

"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # true

# repeat("A", 10)
'A'^10 # "AAAAAAAAAA"
"B"^10 # "BBBBBBBBBB"
"BA"^10 # "BABABABABABABABABABA"

Range and Vector

V = [i/2 for i in 1:10]

# Comprehensions can also be written without the enclosing square brackets, 
# producing an object known as a generator.
sum(1/n^2 for n=1:1000)

# convert a range to a vector by using the collect function.
vec = collect(1:2:7)
println(vec)  # Output: [1, 3, 5, 7]

Matrix

A = [1 2; 3 4] 
#= 2×2 Matrix{Int64}:
 1  2
 3  4
=#
B = A*A*A
#= 2×2 Matrix{Int64}:
 37   54
 81  118
=#
B == A^3 # true

C = A * 3
C == 3A  # true

sin.(A)
#= 2×2 Matrix{Float64}:
 0.841471   0.909297
 0.14112   -0.756802
=#

sin(A)
#= 2×2 Matrix{Float64}:
 -0.465581  -0.148424
 -0.222637  -0.688218
=#

A*[1,2]
#= 2-element Vector{Int64}:
  5
 11
=#

Dict

Dict("A"=>1, "B"=>2)
#= Dict{String, Int64} with 2 entries:
  "B" => 2
  "A" => 1
=#

List of functions of Collections