immutability,elixir , Are Elixir variables really immutable?


Are Elixir variables really immutable?

Question:

Tag: immutability,elixir

In Dave Thomas's book Programming Elixir he states "Elixir enforces immutable data" and goes on to say:

In Elixir, once a variable references a list such as [1,2,3], you know it will always reference those same values (until you rebind the variable).

This sounds like "it won't ever change unless you change it" so I'm confused as to what the difference between mutability and rebinding is. An example highlighting the differences would be really helpful.


Answer:

Immutability means that data structures don't change. For example the function HashSet.new returns an empty set and as long as you hold on to the reference to that set it will never become non-empty. What you can do in Elixir though is to throw away a variable reference to something and rebind it to a new reference. For example:

s = HashSet.new
s = HashSet.put(s, :element)
s # => #HashSet<[:element]>

What cannot happen is the value under that reference changing without you explicitly rebinding it:

s = HashSet.new
ImpossibleModule.impossible_function(s)
s # => #HashSet<[:element]> will never be returned, instead you always get #HashSet<[]>

Contrast this with Ruby, where you can do something like the following:

s = Set.new
s.add(:element)
s # => #<Set: {:element}>

Related:


Join two tables belong to two database in Elixir Ecto


elixir,ecto
In Elixir, with Ecto, is it possible to join two different tables (in the same host) belonging to different two databases. There are two databases called cloud and cloud_usage in this query When I execute the query, which Repo should I use? Billing.CloudUsage.Repo.all(query) or Billing.Cloud.Repo.all(query) query = from cucu in...

Elixir: Pattern Match or Guard


elixir
I am curious when I should be using pattern matching vs guard clauses when defining functions. For example with pattern matching: defmodule Exponent do def power(value, 0), do: 1 def power(value, n), do: value*power(value, n-1) end vs guard clause: defmodule Exponent do def power(value, n) when n==0, do: 1 def...

What is the number that shows up after you define an anonymous function in elixir?


elixir
When you define an anonymous function in elixir you get a result like this. #Function<6.90072148/1 in :erl_eval.expr/5> What I've noticed is that the number is based on the arity of the function. So a 1 arg function is always #Function<6.90072148/1 in :erl_eval.expr/5> A two arg function is always #Function<12.90072148/2 in...

In Elixir how do you initialize a struct with a map variable


elixir,elixir-framework
I know its possible to create a struct via %User{ email: '[email protected]' }. But if I had a variable params = %{email: '[email protected]'} is there a way to create that struct using that variable for eg, %User{ params }. This gives an error, just wondering if you can explode it...

Immutable `var` array


swift,immutability
I'd like to create an array in Swift that is immutable, but can be completely replaced, in the style of functional programming. I understand that I can create them in this way: var mutable = [1,2,3] // can change reference, add, remove, etc let immutable = [4,5,6] // cannot replace...

Output tabular data with IO.ANSI


elixir
I would like to render a 2-dimensional list to a nice tabular output, using an ANSI escape sequences to control the formatting. So given this data: data = [ [ 100, 20, 30 ], [ 20, 10, 20 ], [ 50, 400, 20 ] ] I would like to output...

Optional POST parameters in Elixir Phoenix


elixir,phoenix-framework
I have a phoenix route that I want to POST some form data to, however there are about 4 fields of the form that are optional (the form is constructed by the end user and therefore these fields may not exist in the POST payload) In the Phoenix controller for...

Ways to signal that API returns an unmodifiable/immutable collection


java,immutability
Other than documenting it (obviously it should also be documented), using a special return type (I'm wary of limiting myself to an ImmutableX) or having the user find out at runtime, is there any other way of telling the users of an API that the collection they receive from said...

how to instruct ecto to not create the auto increment id field?


elixir
Ecto migrations automatically create an auto increment field by name 'id' in the table. How to avoid creating this field? How to set another column in the table as primary key (not auto increment)? ...

How to stub (or prevent running) of a call to a worker in my ExUnit test?


elixir,phoenix-framework
I have a Phoenix app (which is just a restful api with no front end) and one of the controllers does some stuff which I want to test, but at the end of the controller it calls a dispatcher which sends a payload off to a worker (run under poolboy)...

Immutable Objects & Updates


java,database,hibernate,jpa,immutability
If I'm using an immutable class named Name that stores people's names, and someone wants to change their name shouldn't their name be updated (essentially delete the old entry and insert the new entry)? This appears to contradict the definition (by the annotation) of immutable as updating the entity will...

What does BEAM stand for in iex for the Elixir programming language?


architecture,elixir,acronym,beam,lightweight-processes
I'm sort of curious as to what the B. E. A. and M. stand for. I recall seeing an explanation of the acronym BEAM, but I have not managed to find it again. It comes up in error codes: ➜ gentoo iex Erlang/OTP 17 [erts-6.4.1] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false]...

How are Strings created and stored in Java?


java,string,memory-management,immutability,hashcode
To understand how String objects are created and stored, I tried the following program and I see output against which I have query. Can somebody please help? package corejava.immutable; public class StringTester { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = "Omkar Patkar"; String...

How to run Elixir application?


elixir
What is the correct way to run an Elixir application? I'm creating a simple project by: mix new app and after that I can do: mix run which basically compiles my app once. So when I add: IO.puts "running" in lib/app.ex I see "running" only for the first time, each...

Is that possible to get comments with macro?


macros,elixir
I was trying to parse some code and reformat them, but it seems that quote will just ignore the comments. Is there any way to achieve this? I guess I have to dive into the erlang side?...

What is this thing called in Java?


java,oop,object,inheritance,immutability
Google isn't being very friendly today, and I'm researching some OOP techniques I've not used in the past. Basically, I've noticed some libraries have variables with preset choices, like new Website(Websites.STACKOVERFLOW). What is that called, when you've got apparently immutable values like that? What if I want to create my...

Is this compromise to string immutablity in java? [duplicate]


java,string,immutability,string-pool
This question already has an answer here: Is a Java string really immutable? 13 answers All of us know that String is immutable in java - content can not be changed once the string is created. String uses character array char[] value to store string content, here is the...

Dictionaries and lists appear immutable when passed to function


python,list,dictionary,immutability
I thought that dictionaries and lists were mutable in Python. What explains this behavior? #!/usr/bin/python3 def change_list(l): l = ['changed!'] def change_dict(d): d = {'changed!'} mydict = {'bob': ['blah', 5], 'asdf' : 'asdf'} change_dict(mydict) print(mydict) mylist = ['hello', 'foo', 'bar'] change_list(mylist) print(mylist) Output: $ python3 test3.py {'asdf': 'asdf', 'bob': ['blah',...

Why the syntax for defining sigils in Elixir doesn't use “defsigil”?


elixir,sigils
I was reading the page about sigils in the Elixir tutorial. I expected the syntax for defining sigils uses "defsigil" just like "defstruct", "defprotocol", and so on. But it was not so. Why?

How to Log something in Controller when Phoenix Server is running?


elixir,phoenix-framework
Well, the question is pretty clear. I'm trying to print some debug information from one of my Controllers in my Phoenix App when the Server is running. defmodule PhoenixApp.TopicController do use PhoenixApp.Web, :controller alias PhoenixApp.Topic plug :action def index(conn, _params) do # ... log "this text" # ... render(conn, "index.html")...

Phoenix: Broadcasting from IEx console


elixir,phoenix-framework
I have built a small chat app like the one here: https://github.com/chrismccord/phoenix_chat_example/blob/master/web/channels/room_channel.ex And cannot figure out how to broadcast to all users in a topic a message. In the above application (which isn't updated to v0.13 like I'm using), how would I do that? Below is what I've tried with...

Sort List elements in Elixir Lang


elixir
I have a list of strings that I want to order in two ways. Alphabetically By string length ...

Memory consumption when chaining string methods


c#,string,immutability,method-chaining
I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string? If it is true, what is the best practice to do too many manipulations on a string using chaining methods?...

Wait for Node.connect before using :global.whereis_name


erlang,elixir
I have the following function: def join(id) do if Node.connect(:"#{id}@127.0.0.1") do send :global.whereis_name(id), {:join, id} end end I receive the error: (ArgumentError) argument error :erlang.send(:undefined, ... which I assume is because Node.connect does some gathering of information and when I call :global.whereis_name it has not finished yet. If I throw...

How to rewrite Erlang combinations algorithm in Elixir?


functional-programming,erlang,elixir
I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck. Erlang version: comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T). Elixir version I came up with...

How Instances of immutable types are inherently thread-safe


c#,thread-safety,immutability
I search about Why .NET String is immutable? And got this answer: Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interfers with another is removed (the reference itself is a different matter). So I...

Getting a sibling process in Elixir


erlang,elixir,otp
I have an Elixir/Erlang process tree: parent (Supervisor) ├── child1 (GenServer) └── child2 (GenServer) child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1?...

Horribly redundant Phoenix controller


elixir,phoenix-framework,ecto
I'm doing my first Phoenix application, and trying to do new/2 controller. The code I wrote is def new(conn, %{"fbid" => fbid, "latitude" => lat, "longitude" => lng, "content" => content}) do {fbid, _} = Integer.parse(fbid); {lat, _} = Float.parse(lat); {lng, _} = Float.parse(lng); chats = %Chat{:fbid => fbid, :latitude...

Where can I put my Plugs and then use them from different controllers in my Phoenix app?


elixir,phoenix-framework
I'm creating my first Elixir-Phoenix app. I've written a few plugs that I want to use in multiple controllers, right now there is a lot of code duplication since the Plug code is being repeated in all of my controllers. My question is, is there a file where I can...

“Cannot begin test transaction because we are already inside one”


elixir,phoenix-framework,ecto
I followed this tutorial and my simple test always fail with this error 1) test /index returns a list of contacts (WorldNote.ChatsControllerTest) test/controllers/chats_controller_test.exs:16 ** (RuntimeError) cannot begin test transaction because we are already inside one stacktrace: (ecto) lib/ecto/adapters/sql.ex:321: anonymous fn/6 in Ecto.Adapters.SQL.start_test_transaction/3 (ecto) lib/ecto/adapters/sql.ex:615: Ecto.Adapters.SQL.pool_transaction/4 (ecto) lib/ecto/adapters/sql.ex:314: Ecto.Adapters.SQL.start_test_transaction/3...

Fill immutable map with for loop upon creation


scala,dictionary,collections,initialization,immutability
I have this map that looks like this: val fields: Map[(Int, Int), Field] and I thought about doing something like: val fields: Map[(Int, Int), Field] = Map( for(a <- 0 to 10) { (0, a) -> new Field(this, 0, a) } ) instead of a long copy/paste list like: (0,...

Should every object in the store state be immutable?


javascript,reactjs,immutability,flux,immutable.js
I am learning React.js and Flux, and I understand that is better to keep the object immutable because comparing them is O(1). My situation is this: I have a store, which has a _state object, that is a map (I'm using Immutable-js). That _state has some booleans, some strings and...

Elixir exrm release crashes on eredis start_link


erlang,elixir,exrm
I'm fairly new to Elixir and this is the first app that I'm attempting to release using exrm. My app interacts with a Redis database for consuming jobs from a queue (using exq), and also stores results of processed jobs in Redis using eredis. My app works perfectly when I...

Java immutability when defining members in a function called by constructor


java,class,design-patterns,design,immutability
I have class like this: abstract class Parent { protected Parent(Raw rawData) { deserialize(rawData); } protected abstract void deserialize(Raw rawData); } class Child extends Parent { final byte firstByte; public Child(Raw rawdData) { super(rawData); } protected void deserialize(Raw rawData) { firstByte = rawData.getFirst(); } } So basically any child class...

What is the difference between member val and member this in F#?


.net,f#,immutability
When I created a class containing a generic, mutable .NET Stack in F# like the example below, that stack ignores anything I push onto it. open System.Collections.Generic type Interp(code: int array) = member val PC = 0 with get, set member this.stack: Stack<int> = new Stack<int>() member this.Code = code...

Converting mutable java classes to immutable scala classes


scala,immutability
I have a class which functions something like this class OutputFile(name: String, index: Int = 0){ val localFile = File.createTempFile(name, ".gz") localFile.deleteOnExit() val localFileOut =new FileOutputStream(localFile) private[this] var bytesWritted: Int = 0 def write(line: Bytes): OutputFile = { if(bytesWritten > SOMESIZE) flush //this function uploads the file to a different...

Importing test code in elixir unit test


elixir,mix
I'm writing tests of some Elixir code that interacts with SSH. In my tests, I'd like to start an SSH server that I can run my code against. I'd prefer to store this code in it's own file in the test directory, and have it imported by various different tests....

Cannot borrow as immutable - String and len()


rust,immutability,mutability,borrow-checker
let mut result = String::with_capacity(1000); result.push_str("things... "); result.push_str("stuff... "); result.truncate((result.len() - 4)); However, this is a compile error. Something to do with the borrow checker and possibly mutability. multipolygon.rs:63:21: 63:27 error: cannot borrow `result` as immutable because it is also borrowed as mutable multipolygon.rs:63 result.truncate((result.len() - 2)); ^~~~~~ multipolygon.rs:63:4: 63:10...

Does using private setters only in a constructor make the object thread-safe?


c#,thread-safety,immutability
I know that I can create an immutable (i.e. thread-safe) object like this: class CantChangeThis { private readonly int value; public CantChangeThis(int value) { this.value = value; } public int Value { get { return this.value; } } } However, I typically "cheat" and do this: class CantChangeThis { public...

How to delete a Phoenix Session?


elixir,phoenix-framework
I'm going through the Phoenix Guide on Sessions. It explains it very well how I can bind data to a session using put_session and fetch the value later using get_session but it doesn't tell how I can delete a User's session. From the guide: defmodule HelloPhoenix.PageController do use Phoenix.Controller def...

How Can We Clear the Screen in Iex on Windows


windows,elixir
Please how can we clear the screen in Iex on Windows Documented method in Iex help does not work: clear/0 — clears the screen This StackOverflow Answer also does not work in Windows....

Setting up custom response for exception in Phoenix Application


elixir,phoenix-framework,ecto
im writing phoenix application with ecto and have the following snippet in the test {:ok, data} = Poison.encode(%{email: "[email protected]", password: "mypass"}) conn() |> put_req_header("content-type", "application/json") |> put_req_header("accept", "application/json") |> post(session_path(@endpoint, :create), data) > json_response(:not_found) == %{} this throws a Ecto.NoResultsError i have this defined defimpl Plug.Exception, for: Ecto.NoResultsError do def...

Phoenix - controller with multiple render


elixir,phoenix-framework
Trying to create an app with Elixir + Phoenix, that would be able to handle both "browser" and "api" requests to handle its resources. Is it possible to do it without having to do something like that : scope "/", App do pipe_through :browser resources "/users", UserController end scope "/api",...

BSTD inorder traversal produces erroneous behaviour


java,debugging,recursion,immutability
I have a BSTD implementation which is inserting values incorrectly and I can't find for the life of me what is going on. EXPECTED ACTUAL -------- ---------- Alex Janice Carlos Janice Elton Janice Janice Zidane Zidane Zidane Implementation private Node<K,E> insert(Node<K,E> node, K key, E elem) { if (node ==...

JavaScript - Why does the increment operator modify immutable strings?


javascript,string,immutability,nan
In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string. However, I was playing around in jsconsole and found an exception string = "string"; string + 37; => "string37" string; => "string" The original...

Why Rem operator in Elixir returns negative numbers?


elixir
I am trying a simple operation rem(-1, 25) I expect that to be the reminder of integer division and return 24 (the same e.g. as in Ruby) but it returns -1. Am I doing something wrong? Is the behavior broken on elixir?...

Rails' before_filter equivalent in Phoenix


ruby-on-rails,elixir,phoenix-framework
I've just started working on my first Phoenix app, and the issue is that I have some common lines of code in every action in my controller, that I would like to separate out. These lines fetch data from multiple Ecto Models and saves them to variables for use. In...

Most efficient way to search file for byte patterns in Elixir


elixir,id3
I am searching for id3 tags in a song file. A file can have id3v1, id3v1 extended tags (located at the end of the file) as well as id3v2 tags (usually located at the beginning). For the id3v1 tags, I can use File.read(song_file) and pull out the last 355 bytes...

Which OTP behavior should I use for an “endless” repetition of tasks?


elixir,otp,phoenix-framework
I want to repeatedly run the same sequence of operations over and over again next to a Phoenix application (without crashing the whole web-app if something brakes in the worker of course) and don't really know wether I should use a GenServer, Elixir's Tasks, an Agent or something completely different...

Scala: How to compute the sum of all elements in the leaves of a Binary Tree?


scala,sum,binary-tree,immutability,case-class
I'm learning Scala by working the exercises from the book "Scala for the Impatient". Given the following way to model binary trees with case classes, one question asks to compute the sum of all elements in the leaves. sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class...