Elixir – Char lists ”; Previous Next A char list is nothing more than a list of characters. Consider the following program to understand the same. Live Demo IO.puts(”Hello”) IO.puts(is_list(”Hello”)) The above program generates the following result − Hello true Instead of containing bytes, a char list contains the code points of the characters between single-quotes. So while the double-quotes represent a string (i.e. a binary), singlequotes represent a char list (i.e. a list). Note that IEx will generate only code points as output if any of the chars is outside the ASCII range. Char lists are used mostly when interfacing with Erlang, in particular old libraries that do not accept binaries as arguments. You can convert a char list to a string and back by using the to_string(char_list) and to_char_list(string) functions − Live Demo IO.puts(is_list(to_char_list(“hełło”))) IO.puts(is_binary(to_string (”hełło”))) The above program generates the following result − true true NOTE − The functions to_string and to_char_list are polymorphic, i.e., they can take multiple types of input like atoms, integers and convert them to strings and char lists respectively. Print Page Previous Next Advertisements ”;
Category: elixir
Elixir – Recursion
Elixir – Recursion ”; Previous Next Recursion is a method where the solution to a problem depends on the solutions to smaller instances of the same problem. Most computer programming languages support recursion by allowing a function to call itself within the program text. Ideally recursive functions have an ending condition. This ending condition, also known as the base case stops reentering the function and adding function calls to the stack. This is where the recursive function call stops. Let us consider the following example to further understand the recursive function. Live Demo defmodule Math do def fact(res, num) do if num === 1 do res else new_res = res * num fact(new_res, num-1) end end end IO.puts(Math.fact(1,5)) When the above program is run, it generates the following result − 120 So in the above function, Math.fact, we are calculating the factorial of a number. Note that we are calling the function within itself. Let us now understand how this works. We have provided it with 1 and the number whose factorial we want to calculate. The function checks if the number is 1 or not and returns res if it is 1(Ending condition). If not then it creates a variable new_res and assigns it the value of previous res * current num. It returns the value returned by our function call fact(new_res, num-1). This repeats until we get num as 1. Once that happens, we get the result. Let us consider another example, printing each element of the list one by one. To do this, we will utilize the hd and tl functions of lists and pattern matching in functions − Live Demo a = [“Hey”, 100, 452, :true, “People”] defmodule ListPrint do def print([]) do end def print([head | tail]) do IO.puts(head) print(tail) end end ListPrint.print(a) The first print function is called when we have an empty list(ending condition). If not, then the second print function will be called which will divide the list in 2 and assign the first element of the list to head and the remaining of the list to tail. The head then gets printed and we call the print function again with the rest of the list, i.e., tail. When the above program is run, it produces the following result − Hey 100 452 true People Print Page Previous Next Advertisements ”;
Elixir – Lists and Tuples
Elixir – Lists and Tuples ”; Previous Next (Linked) Lists A linked list is a heterogeneous list of elements that are stored at different locations in memory and are kept track of by using references. Linked lists are data structures especially used in functional programming. Elixir uses square brackets to specify a list of values. Values can be of any type − [1, 2, true, 3] When Elixir sees a list of printable ASCII numbers, Elixir will print that as a char list (literally a list of characters). Whenever you see a value in IEx and you are not sure what it is, you can use the i function to retrieve information about it. Live Demo IO.puts([104, 101, 108, 108, 111]) The above characters in the list are all printable. When the above program is run, it produces the following result − hello You can also define lists the other way round, using single quotes − Live Demo IO.puts(is_list(”Hello”)) When the above program is run, it produces the following result − true Keep in mind single-quoted and double-quoted representations are not equivalent in Elixir as they are represented by different types. Length of a List To find the length of a list, we use the length function as in the following program − Live Demo IO.puts(length([1, 2, :true, “str”])) The above program generates the following result − 4 Concatenation and Subtraction Two lists can be concatenated and subtracted using the ++ and — operators. Consider the following example to understand the functions. IO.puts([1, 2, 3] ++ [4, 5, 6]) IO.puts([1, true, 2, false, 3, true] — [true, false]) This will give you a concatenated string in the first case and a subtracted string in the second. The above program generates the following result − [1, 2, 3, 4, 5, 6] [1, 2, 3, true] Head and Tail of a List The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail. list = [1, 2, 3] IO.puts(hd(list)) IO.puts(tl(list)) This will give us the head and tail of the list as output. The above program generates the following result − 1 [2, 3] Note − Getting the head or the tail of an empty list is an error. Other List functions Elixir standard library provides a whole lot of functions to deal with lists. We will have a look at some of those here. S.no. Function Name and Description 1 delete(list, item) Deletes the given item from the list. Returns a list without the item. If the item occurs more than once in the list, just the first occurrence is removed. 2 delete_at(list, index) Produces a new list by removing the value at the specified index. Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned. 3 first(list) Returns the first element in list or nil if list is empty. 4 flatten(list) Flattens the given list of nested lists. 5 insert_at(list, index, value) Returns a list with value inserted at the specified index. Note that index is capped at the list length. Negative indices indicate an offset from the end of the list. 6 last(list) Returns the last element in list or nil if list is empty. Tuples Tuples are also data structures which store a number of other structures within them. Unlike lists, they store elements in a contiguous block of memory. This means accessing a tuple element per index or getting the tuple size is a fast operation. Indexes start from zero. Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value − {:ok, “hello”} Length of a Tuple To get the length of a tuple, use the tuple_size function as in the following program − Live Demo IO.puts(tuple_size({:ok, “hello”})) The above program generates the following result − 2 Appending a Value To append a value to the tuple, use the Tuple.append function − tuple = {:ok, “Hello”} Tuple.append(tuple, :world) This will create and return a new tuple: {:ok, “Hello”, :world} Inserting a Value To insert a value at a given position, we can either use the Tuple.insert_at function or the put_elem function. Consider the following example to understand the same − tuple = {:bar, :baz} new_tuple_1 = Tuple.insert_at(tuple, 0, :foo) new_tuple_2 = put_elem(tuple, 1, :foobar) Notice that put_elem and insert_at returned new tuples. The original tuple stored in the tuple variable was not modified because Elixir data types are immutable. By being immutable, Elixir code is easier to reason about as you never need to worry if a particular code is mutating your data structure in place. Tuples vs. Lists What is the difference between lists and tuples? Lists are stored in memory as linked lists, meaning that each element in a list holds its value and points to the following element until the end of the list is reached. We call each pair of value and pointer a cons cell. This means accessing the length of a list is a linear operation: we need to traverse the whole list in order to figure out its size. Updating a list is fast as long as we are prepending elements. Tuples, on the other hand, are stored contiguously in memory. This means getting the tuple size or accessing an element by index is fast. However, updating or adding elements to tuples is expensive because it requires copying the whole tuple in memory. Print Page Previous Next Advertisements ”;
Elixir – Variables
Elixir – Variables ”; Previous Next A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Types of Variables Elixir supports the following basic types of variables. Integer These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory. Floats Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used. Boolean They can take up 2 values which is either true or false. Strings Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings. Anonymous Functions/Lambdas These are functions that can be defined and assigned to a variable, which can then be used to call this function. Collections There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters. Variable Declaration A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following − life = 42 This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e., life = “Hello world” Variable Naming Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional ”?” OR ”!”. Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something. Printing Variables In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable − life = 42 And enter ”life” in your shell, you”ll get the output as − 42 But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function − Live Demo life = 42 IO.puts life or Live Demo life = 42 IO.puts(life) This will give you the following output − 42 Print Page Previous Next Advertisements ”;