Questions tagged [immutability]
Immutability is the inability to modify data after it has been created. Modifications are instead made by copying the data. A property of immutable data is that it is *referentially transparent*.
3,519
questions
0
votes
0
answers
19
views
Primitive data type immutability [duplicate]
I know, that all data types (primitives) in Js except objects are immutable.
So we can't do something:
let str = 'str';
str[0] = 't'; //error in strict mode
But we can do following:
let str = 'str';
...
0
votes
2
answers
46
views
Why does shadowing change the mutability of a variable in this code?
In thie following code,
fn main()
{
let mename : String = String::from("StealthyPanda");
println!("{mename}");
let mename = displayswithhere(mename);
println!(&...
1
vote
1
answer
45
views
In Kotlin how Immutable parameters affect space complexity if you have to copy the input every time to modify it?
In Kotlin, function parameters are immutable, so you cannot modify the parameter in the code without making a copy first, does this affect space complexity, and does it prevent in-place modification, ...
0
votes
0
answers
20
views
Swift library for immutable, persistent hash and vector structures
Clojure, Scala and JavaScript have excellent implementations of Hickey/Bagwell Hash array mapped tries and Vector tries. This allows Clojure to have built-in persistent array and persistent map types ...
0
votes
1
answer
35
views
How does JVM makes raw type wrapper "Immutable" when passing function parameter?
I have a simple code snippet to test "Immutable" integer like below:
public static void changeInteger(Integer i) {
++i;
}
public static void main(String[] args) {
...
3
votes
1
answer
34
views
Matching more than once on the same option creates too many mutable references to self
This is sort of a conceptual question, but this code does not compile:
struct HashHolder{
pub thing: HashMap<usize, usize>,
}
impl HashHolder {
fn insert(&mut self, item: &usize) ...
0
votes
1
answer
41
views
Pyrsistent transformation that allows missing fields
I plan to replace quite complex JSON-like, mutable data structures with their pyrsisent equivalent in Python. I need to change the value belonging to a key if the key exists. In the test function at ...
1
vote
0
answers
24
views
Is there a memory efficient way to change a higher level variable or counter in R with lapply?
I have a function in which a variable is initialized and then modified inside an lapply function.
f <- function() {
a <- 1
lapply(seq_len(1000000), function(i) {
print(paste0('a:'...
1
vote
2
answers
38
views
scala: avoid a var while iterating and accumulating in a functional manner (no vars)
I need help to find the right Scala approach that will make this code more functional and less mutable.
def findMinTime(str: String, timeByCar: Int): Int = {
var myTime = timeByCar
var ...
95
votes
4
answers
6k
views
If Python strings are immutable, why does it keep the same id if I use += to append to it?
Strings in Python are immutable, which means the value cannot be changed. However, when appending to the string in the following example, it looks like the original string memory is modified since the ...
0
votes
0
answers
31
views
Immutability vs Mutability in Python Dataclasses / Pydantic Models. When to use either approach?
Background
I'm building an API based on pydantic that allows one to build a well-defined and validated specification for an application. I'm debating the relative merits of making the model mutable vs ...
0
votes
2
answers
70
views
How to create a GENERATED column containing the MD5 of multiple columns?
I tried to add the following table in PostgreSQL 14.3:
CREATE TABLE client_cache (
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
request VARCHAR COMPRESSION lz4 NOT NULL ...
1
vote
1
answer
23
views
C# MongoDB How to Deserialize to ImmutableList<T>
I just stumbled over this - I registered my Records which include some ImmutableLists.
Basically, like this:
record A {
[BsonId]
string Id {get; init;}
string Name {get; init;}
...
0
votes
1
answer
18
views
About the immutableOpenmap in elasticsearch
I would like to ask what consideration is the immutableOpenmap in Elasticsearch designed for? What kind of utility does it have? It is used in both aliasmetadata and indexmetadata. My personal guess ...
2
votes
1
answer
56
views
data._mutable= True in Django rest framework
I have seen this many times and looked it everywhere but couldn't figure out what it actually means and is it mandatory? I have not used this data._mutable = True or False in my code before and I am ...
1
vote
1
answer
42
views
Change React state in immutable way
I have a state which consists of array of Exam objects one of parameters of it (tasks) is array of objects too. I need to change parameter (status) of one item of parameter array (tasks) in one object ...
6
votes
3
answers
54
views
Preallocate or change size of vector
I have a situation where I have a process which needs to "burn-in". This means that I
Start with p values, p relatively small
For n>p, generate nth value using most recently generated p ...
0
votes
1
answer
39
views
Update a BuiltList from built_value
I want to update the BuiltList in the state if some condition is met. Here is my reducer
TravelDeductionsStateBuilder _travelDeductionBreakfastToggled(
TravelDeductionsStateBuilder state,
...
0
votes
1
answer
57
views
Spring persistent framework which supports data class of kotlin
the question is simple, but I can't find any of answer about this.
After searching, I realize that kotlin data class is not suitable for Spring JPA because data class is immutable and does not support ...
0
votes
1
answer
53
views
How to create inmutable and singleton objects in python?
I'm trying to create a class that holds some data and is "shared" in all the code. Like the strings in Python: they are shared everywhere, as they are immutable, and only one instance with a ...
1
vote
1
answer
52
views
Implement Iterable in an immutable LinkedList in Kotlin
I'm trying to understand the functional programming paradigm so I'm playing around with an immutable linked list. I've created a Bag with some utility functions and now I want to iterate through the ...
0
votes
1
answer
175
views
Can't modify frozen String on Hash
I am a bit confused with the frozen string and utilizing them with test cases.
I just added the following line at the top of my test cases :
# frozen_string_literal: true
And i have the following two ...
-3
votes
3
answers
106
views
Javascript Lodash replace array with another [duplicate]
I'm trying to manipulate an array like this:
data = [
{
"id":"1",
"items":[
{
"title":"item 1"
},
...
0
votes
1
answer
21
views
idiomatic way to represent key-value maps in Redux store
I think that most examples I've seen online, when needing to maintain a key-value map in Redux store, they seem to choose to type it as an array of key-value pairs, e.g.:
employees: [{id: 42, emp: {...
0
votes
1
answer
70
views
Moq - mocking inherited/segregated interfaces
I've got a large QueryModel class that overall looks like this:
public class QueryModel: IQueryModel
{
public int Property1 { get; set; }
... ~100 more fields like this
}
public interface ...
0
votes
1
answer
28
views
Altering an immutable object?
def add_alpha(tuple_in):
list_out = []
for t in tuple_in:
t.append(10)
a = ([1,1], [2,2], [3,3])
b = a
print(id(a), id(b))
add_alpha(a)
print(id(a), id(b))
print(b)
The above ...
3
votes
0
answers
55
views
Returning copies of objects with the spread operator and effects on performance with Javascript
I wanted to make an object where you could not directly mutate the variables so I decided to create what is essentially a store with a reducer similar to redux. When I return the store with the get() ...
0
votes
2
answers
30
views
Freeze variable False / True to change - make it immutable after first change
hope you can help me out.
Default state of the variable is set to "False" and within the "while True" loop I have "if/else" statement which can change the variable to &...
0
votes
0
answers
26
views
Why does applying this function on a dict have side-effects? [duplicate]
I have a list of dictionaries, and I would like to generate a new list whose elements are some function applied to the original list's elements, without making any changes to the original list. If I ...
0
votes
0
answers
23
views
Immutability of string [duplicate]
As I know, immutability of object in python means that when we modify this object, new object being created in computer memory and new object's id and old_object's id are different. Then I can't ...
1
vote
1
answer
91
views
Multiple Immutable References
I have the following code:
use std::collections::HashMap;
fn doublez(h1: &HashMap<String, i32>, h2: &HashMap<String, i32>) {
dbg!(h1, h2);
}
fn main() {
let mut scores = ...
0
votes
0
answers
37
views
What are the advantages of immutable data? [duplicate]
What are the advantages of using immutable libraries like immer.js or immutable.js? What is the difference between making changes to a draft of an object or making changes to a duplicate of the ...
1
vote
1
answer
45
views
Scala better approach or solution - get average diff between list of records
Below are series of record logs:
1,1000,open
2,1000,open
1,1002,close
2,1002,close
The first field is user id, second field time epoch, and third field status of the session. The session time for the ...
1
vote
2
answers
58
views
How can I fix this particular "Val cannot be reassigned" error?
I have this code that keeps giving me a "Val cannot be reassigned" error but I can't seem to change the variable to a var instead of val. I simply want to be able to set a string value to my ...
1
vote
3
answers
37
views
Inability to change string
I am trying to solve a maze question.
maze = [
"#o######",
"# ## #",
"# ## # #",
"# # #",
"## ### #",
"## ## #",
"######e#",
...
2
votes
1
answer
38
views
Does "immutable props" mean you can't call methods of objects on props?
It seems that I can put an HTMLElement such as a Canvas on the props of a child and the child will happily draw on it. And I can see various useful cases where I want to do this sort of thing.
...
0
votes
1
answer
67
views
Is there a reason to keep state completely immutable in React?
Take this example of state:
const [state, setState] = useState({ x: 1, nested: { y: 2, z: 3 } });
The immutable version of a handler to increment the value of y would be as follows:
function ...
1
vote
2
answers
123
views
Why can't we make a relationship attribute in spring data JPA final as well?
An Owner entity has a @ManyToOne - @OneToMany relationship with the teacher entity. When I annotate each like this
@Entity
public class Product {
...
@ManyToOne(cascade = MERGE)
private final Owner ...
0
votes
1
answer
58
views
While loop with next() vs foreach
I was going through some third party code and I ran onto this snippet for going through an array. Since this is a respectful code base I'm wandering what is the secret behind the trouble of moving ...
1
vote
2
answers
63
views
Make variable immutable after initial assignment
Is there a way to make a variable immutable after initializing/assigning it, so that it can change at one point, but later become immutable? I know that I could create a new let variable, but is there ...
0
votes
1
answer
37
views
what happens to a scala map when it is updated and assigned to a var?
Day 3 of learning Scala.
I guess maps are immutable. I was wondering, when we update an immutable map and assign it to a new var, what happens to the old map? Is the memory just immediately freed up?
...
2
votes
3
answers
135
views
How to implement memoization in Scala without mutability?
I was recently reading Category Theory for Programmers and in one of the challenges, Bartosz proposed to write a function called memoize which takes a function as an argument and returns the same one ...
0
votes
1
answer
45
views
No rerender when changing state by Object Spreader
I am currently trying to clean up the code of my Todo app a bit and use more immutability. I have therefore replaced the code in the handleStatus function.
From this:
handleStatus(event) {
let ...
1
vote
0
answers
115
views
How to solve error "scala.collection.mutable.WrappedArray$ofRef cannot be cast to [Ljava.lang.String" for unwrapping map in UDF
I get the error above when I apply my UDF, which is defined as followed:
import org.apache.spark.sql.functions.typedLit
import org.apache.spark.sql.functions.udf
def method_name(map:Map[String, Array[...
0
votes
0
answers
59
views
React immutability
In order to get to know React better, I have been working on a todo app for some time.
The work is stacking up as I try to implement the handleStatus function and the change of the status immutable.
...
3
votes
1
answer
213
views
Performance of programs using immutable objects
Does writing programs with immutable objects cause performance problems? If a given object is immutable and we need to somehow change its state, we have to map it to a new object with a slightly ...
-3
votes
1
answer
30
views
How does an array of numbers and its sorted version strictly equal to each other? [duplicate]
Let's say we have an array of numbers in Javascript:
const arr = [1,3,2,6,5,3];
We sort it using the native sort method:
arr.sort(); // OR arr.sort((a, b) => a - b)
Now how do the unsorted and ...
2
votes
1
answer
64
views
While loop with immutable values in F#
I am using mutable variable in a F# while-do loop, it has been working well so far but I am curious to know if there is a way to make it purely functional and only use immutable data?
Context
The ...
1
vote
1
answer
44
views
Setter in DTO just for integration testing?
I couldn't find the info I'm looking for hence posting here for suggestion and getting to know better approach.
I have an immutable DTO object like:
import com.fasterxml.jackson.annotation.JsonCreator;...
0
votes
1
answer
98
views
Tuples/ Records in JavaScript
I was referring to this link: Future Javascript: Records and Tuples and I was wondering, what is the reasoning behind these?
We can still use Object.freeze with both arrays and objects to achieve this....