Skip to content
Artsiom edited this page Jan 17, 2022 · 29 revisions

Basic Types: Numbers, strings, operators

Numbers

There are 2 built-in types representing numbers: int, float.

all the casts must be explicit:

let money int = 10
let amount float = float(money)

Boolean

Boolean values are of type: bool. They can have either true or false values.

Literal constants

Decimals: 123
Floating point numbers: 123.456

Operations

  • It's supported the standard set of arithmetical operations over numbers (+ - * / %)
  • Comparison end equality operators are
    • Equality checks: a == b and a != b
    • Comparison operators: a < b, a > b, a <= b, a >= b
  • Built-in operations on booleans include
    • or keyword – lazy disjunction
    • and keyword – lazy conjunction
    • ! - negation

Strings

The type of strings is str. Strings can be concatenated and used in the for loop to iterate through the characters.
String literals are written in double quotes.

# Simple string literal
let helloWorld str = "Hello" + " world"

# Iteration over a string value
for character in helloWorld { print(character)}

Control Flow: if, for, while

If Expression

if is an expression, i.e. it returns a value. To return a value use ret keyword

# Traditional usage
var age int = 10
if nextYear { age = 11 }

# With else
if age < 10 {
    ret "Young"
} else if age > 10 and age < 18 {
    ret "Teenager"
} else {
    ret "Adult"
}

# As expression 
let isYoung bool = if age < 10 { ret true } else { ret false}

For loop

For loop iterates through lists.

# same as for (int i = 1; i <= 10; i++) 
for value in range(1, 10) { print(value) }

for value in [1, 2, 3]  print(value) 

While Loop

Just a usual while loop:

var x int = 5
while x > 0 {
    print(x)
    x -= 1
}

Break

It's possible to use break keyword to stop the inner loop.

    for i in range(1, 10) {
        if i == 2 { break }
    }

Variables

It's possible to declare a variable using the var keyword. If you want to declare a constant (read-only variable) use let keyword.

# variable
var name str = "Name"
name = "Edited name"

# constant
let hello str = "Hello"

Lists

Lists are created by using the bracket notation e.x. [1, 2, 3]. Elements must have 1 common type like integers or strings. It's not possible to have such a list: ["hello", 10].

Lists can be of type: IntList, StrList, FloatList, BoolList

There exist default method on lists:

# Create a list
let numbers IntList = [1, 2, 3]

# Get element by index
let first_element int = numbers[0] # Indexation starts from 0
# first_element = 1

# Append element
append(4, numbers)

# Remove element
remove(4, numbers)

let last_element = numbers[numbers.size() - 1] # last_element = 4