Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Basic Types

basic-types.livemd

Basic Types

import IEx.Helpers

Integers

42
is_number(42)
1 + 1
0b1010100
0x2A + 7
1 + 2 * 3
# ouch: "/"c
3 ** 3 + 4 / 7 - 6
rem(17, 7)
div(17, 7)

Integer Size

I’d like to know if in Elixir the integers are unbounded, like Python integers, or have a fixed size (probably 32 bits or 64 bits). Since the largest signed $n$-bit integer is $2^{n-1}$, the largest 64-bit signed integer is

2 ** (64 - 1)

Since experimentally we can generate much larger integers

2 ** 1000

we can infer that Elixir’s integers are (effectively) unbounded and that we will never have to worry about integer overflows. 👍

Floating-Point Numbers

I bet that Elixir is using the standard double IEEE 754 format to represent floating-point numbers, a.k.a. “floats”, exactly like Python (and many, many, many other programming languages).

This format doesn’t use a decimal representation of numbers but a binary one. This has the surprising side-effect of introducing round-of errors in the representation of simple (decimal) numbers such as 0.1 or 0.2. So my test to confirm my assumption is to try the (in)famous sum 0.1 + 0.2 which should be “obviously incorrect”:

0.1 + 0.2

Elixir is a bit more strict than Python when it comes to the literal representation of floats. Python will gladly accept the syntax 1. instead of 1.0, or .1 instead of 0.1. On the contrary, Elixir’s floats shall contain a dot and at least one digit before and after the dot.

# 👍
0.1
.1 # 👎
1. # 👎

🚧 TODO

  • exponents,

  • 0-, inf, nan ?

  • Math stuff, sin, cos, etc?

Floats & Integers

1 / 2
# TODO: trunc, ceil, floor (inc for negative numbers)
is_float(4.2)
round(42.7)
trunc(89.7)
trunc(-89.7)
ceil(41.9)
floor(-89.8)
# ceil
# +

Booleans

false
true
true and false
(true and false) or true
true != false
not true
is_boolean(true)

Atoms

:orange
true
nil
:apple == :orange
:😀
is_atom(:yala)

Strings

"Hello world! 👋"
IO.puts("Hello world! 👋")
"break
lines"
"\t\t---\n---\t\t"
"\xe7"
is_binary("Hello")
"jdskdsjk" <> "kdlsdksl"
h = "Hello world! 👋"
h
byte_size(h)
String.length(h)
"the message is: #{h}"
String.upcase("Sébastien")

(Anonymous) Functions

greet = fn name -> IO.puts("Hello #{name}") end
greet.("Sébastien")
is_function(greet)
is_function(greet, 0)
is_function(greet, 1)
is_function(greet, 2)
x = 1

(fn ->
   _x = 1
   1
 end).()

(Linked) Lists

[1, 2, 3]
[1, 2, 3] + [4, 5, 6]
[1, 2, 3] ++ [4, 5, 6]
length([0, 1, 2])
is_list([1, 2, 3])
list = [1, 2, 3]
hd(list)
tl(list)
hd([])
[11, 12]
'👋'
i('👋')
h(List)
i("Help")
i("\xe7")
l = [0, 1, 2]
l = [-1, 2, 7]

Tuples

t = {:ok, nil, 42}
tuple_size(t)
elem(t, 0)
t2 = put_elem(t, 0, :nope)
t2
t