Enumeration ids, disallowed in match operation? - scala-2.8

I have an Enumeration class, and have extracted "id" values from some of the members and stored them in Int variables. Whether that was a good idea/not is not the question.
What the question is, is why I cant seem to do the following:
Let's say I have s : Int which holds one of these id values ... and I would like to do matching against the actual enumeration values. Something like the following:
s match {
QID.MEM_RD.id => // something
QID.MEM_WRT.id => // something else
}
This seems to give me a failure that "stable identifier is required". So I end up writing code like
if (s == QID.MEM_RD.id)
// something
else if (s == QID.MEM_WRT.ID)
// something else
So .. it's just kind of odd to me that Scala has this nice feature, but appears to force me to go back to an uglier style of coding --- when I would much rather use their match feature.
Any ideas? I guess I can restructure to stop extracting ids ... but it's just the idea that match doesn't allow this that irks me a bit.
(Note: I don't try to store the id values anywhere persistently ... just use them for the duration of program execution.)
-Jay

I think you can use if guards in that case.
s match {
case a if (s == QID.MEM_RD.id) => println("you read!")
case b if (s == QID.MEM_WRT.id) => println("you wrote!")
}
http://programming-scala.labs.oreilly.com/ch03.html#PatternMatching

Related

How to find if item is contained in Dict in Julia

I'm fairly new to Julia and am trying to figure out how to check if the given expression is contained in a Dict I've created.
function parse( expr::Array{Any} )
if expr[1] == #check here if "expr[1]" is in "owl"
return BinopNode(owl[expr[1]], parse( expr[2] ), parse( expr[3] ) )
end
end
owl = Dict(:+ => +, :- => -, :* => *, :/ => /)
I've looked at Julia's documentation and other resources, but can't find any answer to this.
"owl" is the name of my dictionary that I'm trying to check. I want to run the return statement should expr[1] be either "+,-,* or /".
A standard approach to check if some dictionary contains some key would be:
:+ in keys(owl)
or
haskey(owl, :+)
Your solution depends on the fact that you are sure that 0 is not one of the values in the dictionary, which might not be true in general. However, if you want to use such an approach (it is useful when you do not want to perform a lookup in the dictionary twice: once to check if it contains some key, and second time to get the value assigned to the key if it exists) then normally you would use nothing as a sentinel and then perform the check get_return_value !== nothing (note two = here - they are important for the compiler to generate an efficient code). So your code would look like this:
function myparse(expr::Array{Any}, owl) # better pass `owl` as a parameter to the function
v = get(expr[1], owl, nothing)
if v !== nothing
return BinopNode(v, myparse(expr[2]), myparse(expr[3]))
end
# and what do we do if v === nothing?
end
Note that I use myparse name, as parse is a function defined in Base, so we do not want to have a name clash. Finally your myparse is recursive so you should define a second method to this function handling the case when expr is not an Array{Any}.
I feel like an idiot for finding this so fast, but I came up with the following solution: (Willing to hear more efficient answers however)
yes = 1
yes = get(owl,expr[1],0)
if yes != 0
#do return statement here
"yes" should get set equal to 0 if the expression is not found in the dictionary "owl". So a simple != if statement to see if it's zero fixes my problem.

How to "leap of faith" when using recursion?

For me when making a recursive method. I always need to spend a lot of time to do it, because I will make some test cases and to see whether my recursive case works and to draw a stack diagram. However, when I ask other about it, they just say that I need to believe myself it will work. How am I suppose to believe that if you don't know what is going on in the recursive case?
You define what is going on in the recursive case, just as you define the rest of the method. Imagine someone else wrote a method to do what the one you are writing does; you wouldn't have a problem calling that, would you? The only difference is that you are that method's author, and it just happens to be the one being written.
For example: I am writing the following method:
// Sort array a[i..j-1] in ascending order
method sort_array( a, i, j ) {
..
}
The base case is easy:
if ( i >= j-1 ) // there is at most one element to be sorted
return; // a[i..j-1] is already sorted
Now, when that isn't true, I could do the following:
else {
k = index_of_max( a, i, j );
swap( a, j-1, k );
At this point, I know that a[j-1] has the correct value, so I just need to sort what comes before it -- fortunately, I have a method to do just that:
sort_array( a, i, j-1 );
}
No leap of faith is required; I know that recursive call will work because I wrote the method to do just that.

Mapping a given value to an action depending on certain characteristics

Suppose I have a certain value, and I want to do something with it depending on certain characteristics it might have.
For example, suppose the value is a string, and I want to print it to the screen if it starts with the letter L, save it to a file if it's length is less than 20 characters, and play a sound if the last character is the same as the first one.
One option of course is a simple if else if construct:
if (value[0] == 'L')
....
else if (value.Length < 20)
....
else if (value[0] == value.Last())
....
However with a lot of conditions, this can get ugly really fast. So the other option is a Dictionary. However I'm not sure how I can use a Dictionary to achieve this.
How can this be done?
You can construct a dictionary that contains conditions and actions that should be performed if a condition is met. In general, if you need to work with type T, this dictionary will have a type Dictionary<Predicate<T>, Action<T>>. For a string it can be:
var conditions = new Dictionary<Predicate<string>, Action<string>>
{
{s => s.StartsWith("L"), s => Console.WriteLine("Starts with L")},
{s => s.Length < 20, s => Console.WriteLine("Has fewer that 20 symbols")},
};
string input = "some input";
foreach (var condition in conditions)
{
if (condition.Key(input)) condition.Value(input);
}
In fact, you don't even need a Dictionary here - you can use List<Tuple<Predicate<string>, Action<string>>>, or, even better - to introduce a simple small class that contains a predicate and an action.

Specman e: Is there a way to constrain the amount of set bits in a number?

I have unit field events:
events:uint;
The values of events not so interesting as the amount of set bits in it. I would like to constrain the ranges of the amount of set bits in the events.
Is there a way to do it?
Thank you for your help.
The operations [..] and %{} aren't generative therefore they considered as inputs in the constraints.
The constraint:
keep events_bits == events[..];
is equivalent to:
keep events_bits == read_only(events[..]);
The generator will generate events and only then will enforce the constraints on `events_bits.
You can do the following:
extend sys {
events : uint;
events_bits_on [32] : list of bool;
keep for each in events_bits_on {
it == (events[index:index] == 1);
};
keep events_bits_on.count(it) == 2;
};
There might be an easier way to do it, but you can use bit slicing to constrain a list of uints to equal the bits of your variable, and use sum to constrain their amount.
The following example does what you need (limited to a 4 bit variable for brevity):
<'
extend sys {
events : uint(bits:4);
b: list of uint(bits:1);
keep b.size() == 4;
keep b[0] == events[0:0];
keep b[1] == events[1:1];
keep b[2] == events[2:2];
keep b[3] == events[3:3];
keep (b.sum(it) == 2);
};
'>
Writing all the constraints is probably a little ugly, but it can easily be done using a define as computed macro.
This is only a partial answer.
You can use events[..] or %{events} to convert from a vector to a list containing the bits of that vector. Using it directly in a constraint directly doesn't work, because it complains there's no generative element:
extend sys {
events : uint(bits:4);
// neither of these compile
keep events[..].sum(it) == value(2);
keep %{events}.sum(it) == value(2);
};
This is probably a case for Cadence.
What is allowed however is to create an intermediate list and assign that to the output of either of these operators:
extend sys {
events_bits : list of bit;
keep events_bits == events[..];
};
You would think that you could then constrain this list to have a certain number of 1s:
extend sys {
// these constraints apply, but aren't enforced
keep events_bits.sum(it) == value(2);
keep events_bits.count(it == 1) == value(2);
};
This doesn't work however. Even though the constraints are there, they don't get enforced for some reason. This is another issue for Cadence to look at.
Summarizing, if these issues weren't there, you could probably count the number of ones easily. Maybe in a future version of Specman. I still hope that at least seeing that the [..] and the %{} operators exist will help you for other things.

How can I simply check if a set of n numbers are all different?

I have n integers and I need a quick logic test to see that they are all different, and I don't want to compare every combination to find a match...any ideas on a nice and elegant approach?
I don't care what programming language your idea is in, I can convert!
Use a set data structure if your language supports it, you might also look at keeping a hash table of seen elements.
In python you might try
seen={}
n_already_seen=n in seen
seen[n]=n
n_already_seen will be a boolean indicating if n has already been seen.
You don't have to check every combination thanks to commutivity and transitivity; you can simply go down the list and check each entry against each entry that comes after it. For example:
bool areElementsUnique( int[] arr ) {
for( int i=0; i<arr.Length-1; i++ ) {
for( int j=i+1; j<arr.Length; j++ ) {
if( arr[i] == arr[j] ) return false;
}
}
return true;
}
Note that the inner loop doesn't start from the beginning, but from the next element (i+1).
You can use a Hash Table or a Set type of data structure that using hashing. Then you can insert all of the elements into the hashtable or hashset, and either as you insert, check if the element is already in the table/set. If for some reason you don't want to check as you go, you can just insert all the numbers and then check to see if the size of the structure is less than n. If it is less than n, there had to be repeated elements. Otherwise, they were all unique.
Here is a really compact Java solution. The time-complexity is amortized O(n) and the space complexity is also O(n).
public boolean areAllElementsUnique(int [] list)
{
Set<Integer> set = new HashSet<Integer>();
for (int number: list)
if (set.contains(number))
return false;
else
set.add(number);
return true;
}

Resources