Append a value in an Array nested in a Dictionary in Swift - dictionary

I have a strange issue with the following code :
var dict = ["KEY" : [1, 2]]
println(dict["KEY"]) // Output is "Optional([1, 2])"
println(dict["KEY"]!) // Output is "[1, 2]"
dict["KEY"]!.append(3) // Error : '(String, Array<Int>)' does not have a member named 'append'
dict["KEY"]! += 3 // Error : type 'DictionaryIndex<String, Array<Int>>' does not conform to protocol 'StringLiteralConvertible'
My goal is to transform the dict variable from ["KEY" : [1, 2]] to ["KEY" : [1, 2, 3]].
I have probably missed something but I don't see what.

Firstly, from apple docs:
Conversely, if you assign an array or a dictionary to a constant, that
array or dictionary is immutable, and its size and contents cannot be
changed.
I think if you assign an array as a value of key within dictionary it goes the same way.
In addition Swift collections are copied whenever they are assigned or passed as a parameter.
If you really want to change array in dict, I guess you may create new array with appended items for example and reassign the value of dict
var arrayInit = [1, 2]
var dict = ["KEY" : arrayInit]
//somewhere
var array = dict["KEY"]!
array.append(3)
dict["KEY"] = array;
println(dict["KEY"]!) // Output is "[1, 2]"

That will do it...
import Cocoa
import Foundation
var dict = ["KEY" : [1, 2]]
println(dict["KEY"]) // Output is "Optional([1, 2])"
println(dict["KEY"]!) // Output is "[1, 2]"
var array = dict["KEY"]!
array.append(3)
array += 3
dict["KEY"] = array

Related

How to store a map using :dets in Elixir?

I want to be able to store a map using :dets
Currently, that is the solution I am trying to implement:
# a list of strings
topics = GenServer.call(MessageBroker.TopicsProvider, {:get_topics})
# a map with each element of the list as key and an empty list as value
topics_map =
topics
|> Enum.chunk_every(1)
|> Map.new(fn [k] -> {k, []} end)
{:ok, table} = :dets.open_file(:messages, type: :set)
# trying to store the map
:dets.insert(table, [topics_map])
:dets.close(table)
However, I get
** (EXIT) an exception was raised:
** (ArgumentError) argument error
(stdlib 3.12) dets.erl:1259: :dets.insert(:messages, [%{"tweet" => [], "user" => []}])
How is it possible to accomplish this?
I have tested by erlang. You should convert the map to list first.
Following from dets:insert_new() doc
insert_new(Name, Objects) -> boolean() | {error, Reason}
Types
Name = tab_name()
Objects = object() | [object()]
Reason = term()
Inserts one or more objects into table Name. If there already exists some object with a key matching the key of any of the specified objects, the table is not updated and false is returned. Otherwise the objects are inserted and true returned.
test code
dets:open_file(dets_a,[{file,"/tmp/aab"}]).
Map = #{a => 2, b => 3, c=> 4, "a" => 1, "b" => 2, "c" => 4}.
List_a = maps:to_list(Map). %% <----- this line
dets:insert(dets_a,List_a).
Chen Yu's solution is good, but before getting it I already found another solution.
Basically, you can just add the map to a tuple
:dets.insert(table, {:map, topics_map})
Then, you can get this map by using
:dets.lookup(table, :map)
As I understood your intent, you want to store users and tweets under separate keys. For that, you need to construct a keyword list, not a map, in the first place.
topics = for topic <- topics, do: {topic, []}
# or topics = Enum.map(topics, &{&1, []})
# or topics = Enum.map(topics, fn topic -> {topic, []} end)
then you might use this keyword list to create dets.
{:ok, table} = :dets.open_file(:messages, type: :set)
:dets.insert(table, topics)
:dets.close(table)

Julia: fields of structs passed by value

In the following piece of Julia code, st.a and b are the same array, so when I delete an element from st.a, then this element is also deleted from b. Is it possible that a new array "*.a" is generated, every time a create an object * of Mystruct?
struct Mystruct
a::Array{Int64,1}
Mystruct(a::Array{Int64,1}) = new(a)
end
b = [1, 2, 3, 4]
st = Mystruct(b)
deleteat!(st.a,1)
I think that:
struct Mystruct
a::Array{Int64,1}
Mystruct(a::Array{Int64,1}) = new(copy(a))
end
will do the job you want.

Index of string value in MiniZinc array

The question
Given a MiniZinc array of strings:
int: numStats;
set of int: Stats = 1..numStats;
array[Stats] of string: statNames;
... with data loaded from a MiniZinc data file:
numStats = 3;
statNames = ["HEALTH", "ARMOR", "MANA"];
How can one look up the index of a specific string in the array? For example, that ARMOR is located at position 2.
The context
I need to find an optimal selection of items with regard to some constraints on their stats. This information is stored in a 2D array declared as follows:
int: numItems;
set of int: Items = 1..numItems;
array[Items, Stats] of float: itemStats;
So in order to write a constraint on, say, the minimum amount of ARMOR obtained through the selected items, I need to know that ARMOR has index 2 in the inner array.
Since the data file is generated by an external program, and the number and order of stats are dynamic, I cannot hardcode the indices in the constraints.
One solution (that won't work in my case)
The MiniZinc tutorial uses an interesting trick to achieve something similar:
set of int: Colors = 1..3;
int: red = 1;
int: yellow = 2;
int: blue = 3;
array[Colors] of string: name = ["red", "yellow", "blue"];
var Colors: x;
constraint x != red;
output [ name[fix(x)] ];
Unfortunately, as variable declarations are not allowed in MiniZinc data files, this trick won't work in my case.
You can write your own custom function to get the index of a string within a string array:
function int: getIndexOfString(string: str,
array[int] of string: string_array) =
sum( [ if str = string_array[i]
then i
else 0 endif
| i in index_set(string_array) ]
);
In this function I create an array of integers where the integer at position i either equals the index of str if string_array[i]=str and 0 otherwise. For instance, for your sample string array ["HEALTH", "ARMOR", "MANA"] and str ARMOR the resulting int array will be [0,2,0].
This is why I can simply sum over the int array to get the index of the string. If the string does not occur, the return value is 0, which is fine since indices in MiniZinc start with 1 by default.
Here is how you can call the function above for your first example:
int: numStats;
set of int: Stats = 1..numStats;
array[Stats] of string: statNames;
numStats = 3;
statNames = ["HEALTH", "ARMOR", "MANA"];
var int: indexOfArmor;
constraint
indexOfArmor = getIndexOfString("ARMOR",statNames);
solve satisfy;
Note however that the function above is limited and has some flaws. First, if you have multiple occurrences of the string in the array, then you will receive an invalid index (the sum of all indices where str occurred). Also, if you have your own index set for your string array (say (2..6)), then you will need to adapt the function.
Another, cleaner option is to write a function that uses a recursive helper function:
% main function
function int: index_of(string: elem, array[int] of string: elements) =
let {
int: index = length(elements);
} in % calls the helper function with the last index
get_index(elem, elements, index)
;
% recursive helper function
function int: get_index(string: elem, array[int] of string: elements, int: index) =
if index == 0
then -1 % the element was not found (base case of recursion)
elseif elements[index] == elem
then index % the element was found
else
get_index(elem, elements, index - 1) % continue searching
endif
;
The helper function iterates recursively over the array, starting from the last element, and when it finds the element, it returns the index. If the element was not found in the array, then -1 is returned. Alternatively, you can also throw an assertion following the suggestion of Patrick Trentin by replacing then -1 with then assert(false, "unknown element: " + elem).
An example of calling this function:
set of int: Customers = 1..5;
array[Customers] of string: ids = ["a-1", "a-2", "a-3", "a-4", "a-5"];
var int: index = index_of("a-3", ids);
var int: unknown_index = index_of("x-3", ids);
where index will be assigned 3 and unknown_index will be -1.
An alternative approach to that presented by Andrea Rendl-Pitrey, is the following one:
array[int] of string: statNames = array1d(10..12, ["HEALTH", "ARMOR", "MANA"]);
var int: indexOfArmor =
sum([i | i in index_set(statNames) where statNames[i] = "ARMOR"]);
solve satisfy;
output [
"indexOfArmor=", show(indexOfArmor), "\n",
];
which outputs:
~$ mzn2fzn example.mzn ; flatzinc example.fzn
indexOfArmor = 11;
----------
note: that var can be dropped from the declaration of indexOfArmor, since the index can be statically computed. I kept it here only for output purposes.
A better solution is to declare a new predicate:
predicate index_of_str_in_array(var int: idx,
string: str,
array[int] of string: arr) =
assert(
not exists(i in index_set(arr), j in index_set(arr))
(i != j /\ arr[i] = str /\ arr[j] = str),
"input string occurs at multiple locations",
assert(
exists(i in index_set(arr))
(arr[i] = str),
"input string does not occur in the input array",
exists(i in index_set(arr))
(arr[i] = str /\ i = idx)
));
which enforces both of the following conditions:
str occurs at least once in arr
str does not occur multiple times in arr
e.g
predicate index_of_str_in_array(var int: idx,
string: str,
array[int] of string: arr) =
...
array[10..13] of string: statNames =
array1d(10..13, ["HEALTH", "ARMOR", "MANA", "ATTACK"]);
var int: indexOfArmor;
constraint index_of_str_in_array(indexOfArmor, "ARMOR", statNames);
solve satisfy;
output [
"indexOfArmor=", show(indexOfArmor), "\n",
];
outputs
~$ mzn2fzn example.mzn ; flatzinc example.fzn
indexOfArmor = 11;
----------
If one changes statNames in the following way
array[10..13] of string: statNames =
array1d(10..13, ["HEALTH", "ARMOR", "MANA", "ARMOR"]);
then mzn2fzn detects an assertion violation:
~$ mzn2fzn example.mzn ; flatzinc example.fzn
MiniZinc: evaluation error:
example.mzn:24:
in call 'index_of_str_in_array'
example.mzn:4:
in call 'assert'
Assertion failed: input string occurs at multiple locations
flatzinc:
example.fzn: cannot open input file: No such file
A similar result would be obtained by searching for the index of a string that does not occur in the array. This condition can of course be removed if not necessary.
DISCLAIMER: older versions of mzn2fzn don't seem to check that the declared index-set of an array of strings variable matches the index-set of an array of strings literal that is being assigned to it. This rule is enforced on newer versions, as it is also valid for other data types.
According to this other post on Stackoverflow there is no way of converting strings to integers in MiniZinc, only the other way around. You need to first pre process your data in some other language and turn it into integers. You can however turn those integers into string once you are done in MiniZinc.
You can however load MiniZinc files instead of data files if you would like. Use the include syntax to include any .mzn file.

Why does map and flatMap behave very differently on a LazyMapCollection?

I have a simple dictionary with String keys and integer values. I wanted to take the integer values from the dictionary and perform an operation on them. An ideal use case for maps. So I tried the following:
let testDict = ["Test0":0, "Test1":1, "Test2":2]
let testValues = testDict.values // Returns a LazyMapCollection
let mapResult = testValues.map( {number in "$\(number).00"} )
print( "mapResult: \(mapResult)" )
let mapFlatResult = testValues.flatMap( {number in "$\(number).00"} )
print( "mapFlatResult: \(mapFlatResult)" )
The mapResult is not what I expected. It returned a LazyMapCollection of a LazyMapCollection of a Dictionary. However, flatMap did return what I expected an array of strings.
mapResult: LazyMapCollection, Int>, String>(_base:
Swift.LazyMapCollection,
Swift.Int>(_base: ["Test1": 1, "Test2": 2, "Test0": 0], _transform:
(Function)), _transform: (Function))
mapFlatResult: ["$1.00", "$2.00", "$0.00"]
Why the difference in implementing between map and flatMap? Is this what map should be doing?
If the LazyMapCollection is turned into an Array it does do the mapping as expected:
print( "mapResult2: " + String(Array(mapResult)) )
mapResult2: ["$1.00", "$2.00", "$0.00"]

JavaFX: concatenating sequences

Is there a standard library function or built-in construct to concatenate two sequences in JavaFX?
Here a Sequences.concatenate() function is mentioned, but it is nowhere to be seen in the official API.
Of course one could iterate over each sequence, inserting the values into a new sequence e.g:
function concatenate(seqA: Object[], seqB: Object[]) : Object[] {
for(b in seqB) insert b into seqA;
seqA;
}
..but surely something as basic as concatenation is already defined for us somewhere..
It is very simple, since there cannot be sequence in sequence (it all gets flattened), you can do it like this:
var a = [1, 2];
var b = [3, 4];
// just insert one into another
insert b into a;
// a == [1, 2, 3, 4];
// or create a new seq
a = [b, a];
// a == [3, 4, 1, 2];
Hope that helps.

Resources