Convert Map <Integer, Long> to array of Integer - collections

Can someone tell me what I am doing wrong here? p.getVote(), and the collection counting logic return a Long, but I am trying to make my end output an array of ints.
Map<Integer, Long> counters = iqr.getQgagueUniqueVotes().stream()
.collect(Collectors.groupingBy(p -> ((int)p.getVote()),
Collectors.counting()));
Collection<Long> values = counters.values();
long[] targetArray = values.toArray(new Long[values.size()]);
Error:
Incompatible type: Inference variable has incompatible upper bound

Change the type of the targetArray array to a type Long:
Long[] targetArray = values.toArray(new Long[values.size()]);
or create a stream of the values and map to a type long then collect to an array.
long[] targetArray = values.stream().mapToLong(Long::longValue).toArray();

Related

Generating tuples containing Long for Vavr Property Checking

I need a pair of random longs for property checking with Vavr.
My implementation looks like this:
Gen<Long> longs = Gen.choose(Long.MIN_VALUE, Long.MAX_VALUE);
Arbitrary<Tuple2<Long, Long>> pairOfLongs = longs
.flatMap(value -> random -> Tuple.of(value, longs.apply(random)))
.arbitrary();
Is any better/nicer way to do the same in vavr?
Arbitrary<T> can be seen as a function of type
int -> Random -> T
Generating arbitrary integers
Because the sample size is of type int, it would be natural to do the following:
Arbitrary<Tuple2<Integer, Integer>> intPairs = size -> {
Gen<Integer> ints = Gen.choose(-size, size);
return random -> Tuple.of(ints.apply(random), ints.apply(random));
};
Let's test it:
Property.def("print int pairs")
.forAll(intPairs.peek(System.out::println))
.suchThat(pair -> true)
.check(10, 5);
Output:
(-9, 2)
(-2, -10)
(5, -2)
(3, 8)
(-10, 10)
Generating arbitrary long values
Currently we are not able to define a size of type long, so the workaround is to ignore the size and use the full long range:
Arbitrary<Tuple2<Long, Long>> longPairs = ignored -> {
Gen<Long> longs = Gen.choose(Long.MIN_VALUE, Long.MAX_VALUE);
return random -> Tuple.of(longs.apply(random), longs.apply(random));
};
Let's test it again:
Property.def("print long pairs")
.forAll(longPairs.peek(System.out::println))
.suchThat(pair -> true)
.check(0, 5);
Output:
(2766956995563010048, 1057025805628715008)
(-6881523912167376896, 7985876340547620864)
(7449864279215405056, 6862094372652388352)
(3203043896949684224, -2508953386204733440)
(1541228130048020480, 4106286124314660864)
Interpreting an integer size as long
The size parameter can be interpreted in a custom way. More specifically we could map a given int size to a long size:
Arbitrary<Tuple2<Long, Long>> longPairs = size -> {
long longSize = ((long) size) << 32;
Gen<Long> longs = Gen.choose(-longSize, longSize);
return random -> Tuple.of(longs.apply(random), longs.apply(random));
};
However, the last example does not match the full long range. Maybe it is possible to find a better mapping.
Disclaimer: I'm the author of Vavr (formerly known as Javaslang)

OCaml: how to create an inductive type with Set argument of same type

In OCaml I can define the following type:
type mytype = Base of int
| Branch of (int * (collection -> collection))
and collection = mytype list
Assuming I define a comparison function based on the int value of each constructor, how can I transform collection to be a Set instead of a list?
This is one of the cases where you will need to use recursive modules. In fact you can see that this is the actual example you get in the documentation of the feature. So something along these lines should do it:
module rec Mytype : sig
type t = Base ...
val compare : t -> t -> int
end = struct
type t = Base ...
let compare v0 v1 = ...
end
and Collection : Set.S with type elt = Mytype.t
= Set.Make (Mytype)

Julia: converting any vector of type to vector of real

I define the type
type mytype
e1:: Real
e2:: Real
end
I want to have a vector of mytype:
Vmtype = Array{mytype}(10)
when I ask julia for the 10 e1. I get an error
Vmtype[1:2].e1
ERROR: type Array has no field e1
How can I access the Vector Vmtype[1:10]?
First, you have to fill in the values of Vmtype. What you are doing is creating an "empty" array of type mytype.
Vmtype = Array{mytype}(10)
e1s = collect(1:10)
e2s = collect(91:100)
for i in 1:10
Vmtype[i] = mytype(e1s[i], e2s[i])
end
then you can access the fields as
Vmtype[1].e1
Notice that one thing is an object of type mytype and another is an array with elements of type mytype. See http://docs.julialang.org/en/latest/manual/types/#man-parametric-types
EDIT:
To create another array with the e1s of Vmtype you can use
Ae1 = map(x -> x.e1, Vmtype)
Then you can use Ae1 in plot((1:10), Ae1).

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

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

Hashtable of mutable variable in Ocaml

I need to use hashtable of mutable variable in Ocaml, but it doesn't work out.
let link = Hashtbl.create 3;;
let a = ref [1;2];;
let b = ref [3;4];;
Hashtbl.add link a b;;
# Hashtbl.mem link a;;
- : bool = true
# a := 5::!a;;
- : unit = ()
# Hashtbl.mem link a;;
- : bool = false
Is there any way to make it works?
You can use the functorial interface, which lets you supply your own hash and equality functions. Then you write functions that are based only on the non-mutable parts of your values. In this example, there are no non-mutable parts. So, it's not especially clear what you're expecting to find in the table. But in a more realistic example (in my experience) there are non-mutable parts that you can use.
If there aren't any non-mutable parts, you can add them specifically for use in hashing. You could add an arbitrary unique integer to each value, for example.
It's also possible to do hashing based on physical equality (==), which has a reasonable definition for references (and other mutable values). You have to be careful with it, though, as physical equality is a little tricky. For example, you can't use the physical address of a value as your hash key--an address can change at any time due to garbage collection.
Mutable variables that may happen to have the same content can still be distinguished because they are stored at different locations in memory. They can be compared with the physical equality operator (==). However, OCaml doesn't provide anything better than equality, it doesn't provide a nontrivial hash function or order on references, so the only data structure you can build to store references is an association list of some form, with $\Theta(n)$ access time for most uses.
(You can actually get at the underlying pointer if you play dirty. But the pointer can move under your feet. There is a way to make use of it nonetheless, but if you need to ask, you shouldn't use it. And you aren't desperate enough for that anyway.)
It would be easy to compare references if two distinct references had a distinct content. So make it so! Add a unique identifier to your references. Keep a global counter, increment it by 1 each time you create a reference, and store the counter value with the data. Now your references can be indexed by their counter value.
let counter = ref 0
let new_var x = incr counter; ref (!counter, x)
let var_value v = snd !v
let update_var v x = v := (fst !v, x)
let hash_var v = Hashtbl.hash (fst !v)
For better type safety and improved efficiency, define a data structure containing a counter value and an item.
let counter = ref 0
type counter = int
type 'a variable = {
key : counter;
mutable data : 'a;
}
let new_var x = incr counter; {key = !counter; data = x}
let hash_var v = Hashtbl.hash v.key
You can put the code above in a module and make the counter type abstract. Also, you can define a hash table module using the Hashtbl functorial interface. Here's another way to define variables and a hash table structure on them with a cleaner, more modular structure.
module Counter = (struct
type t = int
let counter = ref 0
let next () = incr counter; !counter
let value c = c
end : sig
type t
val next : unit -> t
val value : t -> int
end)
module Variable = struct
type 'a variable = {
mutable data : 'a;
key : Counter.t;
}
let make x = {key = Counter.next(); data = x}
let update v x = v.data <- x
let get v = v.data
let equal v1 v2 = v1 == v2
let hash v = Counter.value v.key
let compare v1 v2 = Counter.value v2.key - Counter.value v1.key
end
module Make = functor(A : sig type t end) -> struct
module M = struct
type t = A.t Variable.variable
include Variable
end
module Hashtbl = Hashtbl.Make(M)
module Set = Set.Make(M)
module Map = Map.Make(M)
end
We need the intermediate module Variable because the type variable is parametric and the standard library data structure functors (Hashtbl.Make, Set.Make, Map.Make) are only defined for type constructors with no argument. Here's an interface that exposes both the polymorphic interface (with the associated functions, but no data structures) and a functor to build any number of monomorphic instances, with an associated hash table (and set, and map) type.
module Variable : sig
type 'a variable
val make : 'a -> 'a variable
val update : 'a variable -> 'a -> unit
val get : 'a variable -> 'a
val equal : 'a -> 'a -> bool
val hash : 'a variable -> int
val compare : 'a variable -> 'b variable -> int
end
module Make : functor(A : sig type t end) -> sig
module M : sig
type t = A.t variable.variable
val make : A.t -> t
val update : t -> A.t -> unit
val get : t -> A.t
val equal : t -> t -> bool
val hash : t -> int
val compare : t -> t -> int
end
module Hashtbl : Hashtbl.S with type key = M.t
module Set : Set.S with type key = M.t
module Map : Map.S with type key = M.t
end
Note that if you expect that your program may generate more than 2^30 variables during a run, an int won't cut it. You need two int values to make a 2^60-bit value, or an Int64.t.
Note that if your program is multithreaded, you need a lock around the counter, to make the incrementation and lookup atomic.

Resources