I have a set of ints whose input I'd like to restrict. I would like it to behave something like the following:
# RestrictedIntSet.add 15 (RestrictedIntSet.make 0 10)
Exception: 15 out of acceptable range [0 .. 10]
How can I implement this? In Java, it could look something like:
Set<Integer> restrictedSet = new HashSet<Integer>() {
public boolean add(Integer i) {
if (i < lowerBound || i > upperBound) {
throw new IllegalArgumentException("out of bounds");
}
return super.add(i);
}
Or, to be less abusing of inheritance:
public class RestrictedSet {
private int lowerBound;
private int upperBound;
private Set elems = Sets.newHashSet();
public RestrictedSet(int lowerBound, int upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public boolean add(Integer i) {
if (i < lowerBound || i > upperBound) {
throw new IllegalArgumentException("out of bounds");
}
return elems.add(i);
}
/* fill in other forwarded Set calls as needed */
}
What is the equivalent, idiomatic way to do this in OCaml?
Well, it depends, which set library are you using?
Using the Set module of the standard library, you could do the following:
module type RestrictedOrderedType = sig
type t
val compare : t -> t -> int
val lower_bound : t
val upper_bound : t
end
module RestrictedSet (Elem : RestrictedOrderedType) = struct
include Set.Make(Elem)
exception Not_in_range of Elem.t
let check e =
if Elem.compare e Elem.lower_bound < 0
|| Elem.compare e Elem.upper_bound > 0
then raise (Not_in_range e)
else e
(* redefine a new 'add' in term of the one in Set.Make(Elem) *)
let add e s = add (check e) s
let singleton e = singleton (check e)
end
(* test *)
module MySet = RestrictedSet(struct
type t = int
let compare = compare
let lower_bound = 0
let upper_bound = 10
end)
let test1 = MySet.singleton 3
let test2 = MySet.add (-3) test1
(* Exception: Not_in_range (-3) *)
I like #gasches's answer.
As a short complement: OCaml's Set module is designed to be instantiated by an OrderedType module, which means you cannot directly use OCaml's native ints directly.
One thus needs to use a module that complies with the requested signature. gasche's definition of a RestrictedOrderedType signature does this and elegantly includes the lower and upper bound fields. A rougher approach would be to use OCaml's Int32 or Int64 modules, which conform to the requested OrderedType signature, and hard-code the bounds in the MySet module.
Below is a slight reformulation of gasche's example to illustrate this point.
module MySet = struct
include Set.Make(Int32)
exception Not_in_range of Int32.t
let lower_bound = Int32.of_int 5
let upper_bound = Int32.of_int 10
let add elt set =
if (elt < lower_bound)||(elt > upper_bound)
then raise (Not_in_range elt)
else add elt set
end;;
Related
What is the performance of Groovys collection methods (regarding space(!) and time) in comparison to plain Java for-loops?
Eg for this use cases:
sum() vs. for-loop with variable
each() vs. for-loop with variable
inject() vs. for-loop with variable
collect() vs. for-loop with temporary collection
findAll() vs. for-loop with temporary collection
find() vs. for-loop with variable
So, considering those results, is it advisable to use for-loops over Groovy-collection-methods in critical environments (eg. Grails-WebApp)? Are there resources regarding Groovy/Grails performance (optimization)?
Using this GBench test I got the following results for CPU-time:
user system cpu real
forLoop 2578777 67 2578844 2629592
forEachLoop 2027941 47 2027988 2054320
groovySum 3946137 91 3946228 3958705
groovyEach 4703000 0 4703000 4703000
groovyInject 4280792 108 4280900 4352287
import groovyx.gbench.BenchmarkBuilder
def testSize = 10000
def testSet = (0..testSize) as Set
def bm = new BenchmarkBuilder().run {
'forLoop' {
def n = 0
for(int i = 0; i<testSize; i++) {
n += i
}
return n
}
'forEachLoop' {
def n = 0
for(int i in testSet) {
n += i
}
return n
}
'groovySum' {
def n = testSet.sum()
return n
}
'groovyEach' {
def n = 0
testSet.each { n + it }
return n
}
'groovyInject' {
def n = testSet.inject(0) { el, sum -> sum + el }
return n
}
}
bm.prettyPrint()
Interesting benchmark. No surprise that sum() is slower. Here's how implementation looks like:
private static Object sum(Iterable self, Object initialValue, boolean first) {
Object result = initialValue;
Object[] param = new Object[1];
for (Object next : self) {
param[0] = next;
if (first) {
result = param[0];
first = false;
continue;
}
MetaClass metaClass = InvokerHelper.getMetaClass(result);
result = metaClass.invokeMethod(result, "plus", param);
}
return result;
}
As You can see it must be generic and uses meta programming. The result is bigger time cost.
The results of the benchmark You pasted are clear and pretty self descriptive. If You really need better performance it seems that better idea is to use for loops.
I am passing few values to mail method for sending the details like below
private static String getTeam(String Team, List<String> prioritys1, String number,String description
) {
StringBuilder builder1 = new StringBuilder();
for (String v : prioritys1) {
if ( v == "1") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
else
if ( v == "3") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
}
return builder1.toString();
}
I tried to store in arrays but it didnt worked.
I after pass above parameters, i need to store the value of the number. i need to store the number so that next time while passing the parameters i need to check first whether the number is already passed or not if not then only i need to pass to mail.
can any one help on this
With this code very complicated understand what you are doing. But if you need check value that already been processed store it outside of the method. Create global class variable:
public class className {
private final List<String> ARRAY = new ArrayList<>(); // global variable
public void yourMethod(String value) {
if (!ARRAY.contains(value)) {
mail(value);
ARRAY.add(value);
}
}
}
I dont know your case and I can not get better example.
You need to store the value in a "class level" variable. Whether the variable type needs to be static or instance will depend on your implementation of the method.
If you can post a sample code, we can help further.
You need to compare with 2 equals and not 1
Instead of
if( Team = A )
you need this way
if( Team == A )
Using Team = A, your saying that every time your code reaches that line it will equal Team to A.
Does anyone have background on the java annotation "java.lang.Synthetic". I'm encountering it while listing annotation occurrences in a JavaEE Enterprise Application. The annotation occurs on a couple of classes in package com.sun.xml. I am finding no documentation for this annotation. Is it an official annotation, say, produced by the java compiler to indicate a synthetic accessor (see, for example, Synthetic accessor method warning)? That seems unlikely, since no documentation is available. However, placement in package "java.lang" gives the annotation somewhat of an official look.
Maybe this is what you're looking for?
http://javapapers.com/core-java/java-synthetic-class-method-field/
A perusal of ASM shows this to be a "virtual" parameter annotation added by ASM.
See:
http://asm.ow2.org/index.html
http://websvn.ow2.org/filedetails.php?repname=asm&path=%2Ftrunk%2Fasm%2Fsrc%2Forg%2Fobjectweb%2Fasm%2FClassReader.java
With:
private void readParameterAnnotations(int v, final String desc,
final char[] buf, final boolean visible, final MethodVisitor mv) {
int i;
int n = b[v++] & 0xFF;
// workaround for a bug in javac (javac compiler generates a parameter
// annotation array whose size is equal to the number of parameters in
// the Java source file, while it should generate an array whose size is
// equal to the number of parameters in the method descriptor - which
// includes the synthetic parameters added by the compiler). This work-
// around supposes that the synthetic parameters are the first ones.
int synthetics = Type.getArgumentTypes(desc).length - n;
AnnotationVisitor av;
for (i = 0; i < synthetics; ++i) {
// virtual annotation to detect synthetic parameters in MethodWriter
av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false);
if (av != null) {
av.visitEnd();
}
}
for (; i < n + synthetics; ++i) {
int j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible);
v = readAnnotationValues(v + 2, buf, true, av);
}
}
}
I have a two-dimensional array in Java that looks like this:
Each element/job has a:
Job number which is in index[0];
Job arrival time which is in index[1]; and
Job burst time in index[2]
jobs[0][0] = 1
jobs[0][1] = 0
jobs[0][2] = 5
jobs[1][0] = 2
jobs[1][1] = 2
jobs[1][2] = 19
jobs[2][0] = 3
jobs[2][1] = 4
jobs[2][2] = 10
First, I wanted to sort them according to arrival time which is according to index[1] which fortunately I did by using this code:
Arrays.sort(jobs, new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
Now, my problem is I want to sort it according to burst time which is according to index[2]. Here is the TWIST... How can I be able to sort it according to burst time (index[2]) skipping the first element?
I would like job[0] to remain on top of the array and sort the remaining elements by index[2] - burst time. Like this:
jobs[0][0] = 1
jobs[0][1] = 0
jobs[0][2] = 5
jobs[1][0] = 3
jobs[1][1] = 4
jobs[1][2] = 10
jobs[2][0] = 2
jobs[2][1] = 2
jobs[2][2] = 19
The jobs are being sorted by burst time with job1 remaining on top. Implementing it by the code I provided above would be much better. Thanks
First of all, you should use collections instead of arrays. And second, you should not use an array when you could use an object:
public class Job {
private int number;
private int arrival;
private int burst;
// constructor and getters omitted for brevity.
}
You could then have a List<Job>, instead of an int[][]. Just by looking at the typeof the structure, it's already clearer and more readable. Having named attributes, potentially of different types, and being able to add behavior with methods, is a part of what OO is all about. Much more readable, safe and maintainable than an int[].
The good news is that a List has much more features than an array. So you can for example, take a subList, and sort that subList:
List<Job> jobsExceptFirstOne = allJobs.subList(1);
Collections.sort(jobsExceptFirstOne, new Comparator<Job>() {
#Override
public int compare(Job left, Job right) {
return Integer.compare(left.getBurst(), right.getBurst());
}
});
VoilĂ . Problem solved.
A trivial way would be:
int firstBurst = jobs[0][2];
jobs[0][2] = Integer.MIN_VALUE;
Arrays.sort(jobs, new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
// don't use subtraction, this can lead to underflows
return a[2] < b[2] ? -1 : (a[2] == b[2] ? 0 : 1);
}
});
jobs[0][2] = firstBurst;
Simply set the burst of the first item to Integer.MIN_VALUE (the integer equivalent of minus infinity). That way, it guaranteed that the first item is the smallest, so after sorting it will still be the first element. After sorting, reset the burst of the first item to its original value.
EDIT
By checking the documentation to verify that Arrays.sort is stable, I accidentally found the simplest version to solve this problem: use
Arrays.sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
then you can do this directly:
Arrays.sort(jobs, 1, jobs.length, new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
// don't use subtraction, this can lead to underflows
return a[2] < b[2] ? -1 : (a[2] == b[2] ? 0 : 1);
}
});
As stated by others, you should be using smarter collections instead of arrays, if you really want to use current code, you can use something like:
final int[][] jobs = new int[][]{{1,0,5},{2,2,19},{3,4,10}};
Arrays.sort(jobs, new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
if(Arrays.equals(a, jobs[0]))
return -1;
else
return a[2] - b[2];
}
});
System.out.println(jobs[0][2]);
System.out.println(jobs[1][2]);
System.out.println(jobs[2][2]);
The only drawback is your array needs to be final.
Maybe there would be a way of using this:
final Integer job1 = Integer.valueOf(jobs[0][0]);
final Integer job2 = Integer.valueOf(jobs[0][1]);
return job1.compareTo(job2);
I dont really know if valueOf(jobs[0][0]) would be bigger then valueOf(jobs[0][1]), and I dont really know how they stand to one and another, but there must be a difference between them, and with that you should be a able to sort them according to if the returned number is bigger or smaller then the one of jobs[0][0], jobs[1][0], etc.
Use a Comparator taht remembers the job number of the first job, and regards that as the smallest prior to checking burst time.
public class MyComparator implements Comparator<int[]> {
private final int firstJob;
public MyComparator(int firstJob) {
this.firstJob = firstJob;
}
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) {
return 0;
}
if (a[0] == firstJob) {
return -1;
}
if (b[0] == firstJob) {
return 1;
}
return Integer.compare(a[2], b[2]);
}
}
I am attempting to interop to this simple scala code, but am having some troubles.
package indicators
class DoubleRingBuffer(val capacity:Int=1000) {
var elements = new Array[Double](capacity);
private var head=capacity-1
private var max=0
def size ():Int = {
return max+1
}
def add(obj:Double):Double = {
head-=1
if (head<0) head=capacity-1
return set(max+1,obj)
}
def set(i:Int,obj:Double):Double = {
System.out.println("HI")
if (i>=capacity || i<0)
throw new IndexOutOfBoundsException(i+" out of bounds")
if (i>=max) max=i
var index = (head+i)%capacity
var prev = elements(index)
elements(index)=obj
return prev
}
def get(i:Int=0):Double = {
System.out.println("size is "+size())
if (i>=size() || i<0)
throw new IndexOutOfBoundsException(i+" out of bounds")
var index = (head+i)%capacity
return elements(index)
}
}
In clojure, i do this
(import 'indicators.DoubleRingBuffer)
(def b (DoubleRingBuffer. 100))
(pr (.size b)) ;;ERROR: No matching field found: size for class indicators.DoubleRingBuffer
(pr (.get b 33)) ;;returns 0: should throw an index out of bounds error!
(pr (.get b 100)) ;;throws index out of bounds error, as it should
In addition, i do not get any output to the console! Testing this code using scala works as expected. Whats going on here and how can i fix it so that clojure can use the scala code?
Try these in REPL:
(class b) will probably tell you it's indicators.DoubleRingBuffer.
(vec (.getDeclaredMethods (class b))) will give you a vector of all methods declared in your class as if it was a Java class, so you can see their signatures.
Now, call your methods as seen in the signatures, with these method names and parameters.
I have a feeling the problem is in Scala's dealing with default value for method parameter.
EDIT: As OP described in a comment, it isn't.
If that doesn't work you can try to decompile your Scala bytecode to Java to find out how does DoubleRingBuffer class look like.