Complex case values in Swift - select

Swift has a rather nifty switch statement by the looks of it (at least compared to the other C derivatives) in that you can use values, lists, tuples, ranges and so on.
Its sequential processing nature makes this a very logical approach, but I'm wondering whether it supports more arbitrary objects for checking against, such as variables and other general expressions, such as with:
let check = 7
switch (value) {
case check:
println("exact");
case check * 2:
println("twice");
case check * 3:
println("thrice");
case valueInDb("mytable","mycolumn"):
println ("value in database");
default:
println("some other value");
}

What you are doing is called "Expression Pattern"
From this document:
An expression pattern represents the value of an expression. Expression patterns appear only in switch statement case labels.
The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true. By default, the ~= operator compares two values of the same type using the == operator.
...
expression-pattern → expression­
So you can use any "expression" in switch case, and by default, it will be compared using == operator.

Related

Refer to only lower index in System Verilog

I have a bit array A[32][16].
I want to check if any of the lower index values have a certain pattern.
For eg.
A[1][8:0] may have that pattern A[2][8:0] may also have that pattern.
Any thing from A[31 - 0][8:0] may have that pattern. Is there a way to refer to all the higher index components in a single statement.
something like A[5'bxxxxx][8:0] ?
There is no syntax to select a non-contiguous set of bits from an array, packed or unpacked, in a single selection. If A is an unpacked array, you can use one of the array reduction methods to create an expression that might suit your needs.
if (A.or() with (item[8:0] == your_pattern) ) // if any match
if (A.and() with (item[8:0] == your_pattern) ) // if all match
If A is a packed array, you could use replication concatenation to match all
if ( {32{ {8'b?,your_pattern} } } ?== A )

`switch`-like pattern matching control flow statement that matches any and all true cases?

NOTE: this question is not asking for help solving FizzBuzz. Please don't post answers that just solve FizzBuzz. Answers to this question should relate to matching multiple true switch cases
Consider an attempted FizzBuzz solution in Swift using a switch statement:
func fizzBuzz(forInt int: Int) -> String {
var output = ""
switch 0 {
case (int % 3): output += "Fizz"
case (int % 5): output += "Buzz"
default:
output = String(int)
}
return output
}
// FAILS
assert(fizzBuzz(forInt: 15) == "FizzBuzz", "15 should output `FizzBuzz`, not `Fizz`!")
The correct output on iteration 15 should be "FizzBuzz" because 15 is divisible by both 3 and 5.
But the program above outputs "Fizz" because only the first passing case is executed.
The Swift docs state:
A switch statement executes an appropriate block of code based on the first pattern that matches successfully.
It seems that it would be useful for there to be a similar, switch-like statement that matches any true case rather than just the first.
Pattern matching patterns can currently be used in the following situations:
You use these patterns in a case label of a switch statement, a catch clause of a do statement, or in the case condition of an if, while, guard, or for-in statement.
Matching multiple patterns seems impossible in Swift. Options considered:
fallthrough
Switch fallthrough allows one executed case to fall into and execute the physically next case, but without actually testing the case statement. It does not allow multiple, arbitrary, unordered cases to be executed only if matching.
multiple if statements
Multiple if statements produce the desired behavior, but are annoying for the same reasons switch is often preferred over if-else blocks.
if (i % 3 == 0) {
// ...
}
if (i % 5 == 0) {
// ...
}
Namely re-stating the variable being tested in each case, no compiler protection that we're evaluating the same single variable against multiple cases, etc.
tuples, etc.
Yes, it's possible to do things like switch on a tuple to produce the correct output value. But that involves duplicating code inside the cases.
switch (i % 3, i % 5) {
case (0, 0):
output += "FizzBuzz"
case (0, _):
output += "Fizz"
case (_, 0):
output += "Buzz"
The goal of this question is to have only 2 cases for "Fizz" and "Buzz". Combined execution of the true cases should produce "FizzBuzz", not a separate 3rd case that duplicates the strings.
Related:
Switch to match multiple cases from OptionSetType
Question:
Does there exist a switch-like pattern matching control flow statement that matches any and all true cases? If not in Swift, do any languages contain such a feature?
This loop-nested switch syntax executes each true case in order, not just the first true case.
for i in 1...100 {
var output = ""
for eachCase in 0...1 {
switch (eachCase, 0) {
case (0, i % 3): output += "Fizz"
case (1, i % 5): output += "Buzz"
default: break }
}
if output.isEmpty {
output = String(i)
}
print(output)
}
I'll leave it to the reader to determine situations where this is better behavior than alternative such as multiple if statements.
There was a Swift evolution proposal to introduce a continue statement within Switch cases, which would resume pattern matching against the remaining cases.
[swift-evolution] [Pitch] Introduce continue to switch statements
This proposal completes the switch statement's control flow transfer suite by introducing continue. This change adds functionality that many developers expect (but do not get) from fallthrough.
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160704/023955.html
https://gist.github.com/erica/04835de3d3d9121ef7308dd9b093158a
Introducing continue means "resume pattern matching after executing this case clause". It offers more nuanced control than currently exists within switch.

Julia: Immutable composite types

I am still totally new to julia and very irritated by the following behaviour:
immutable X
x::ASCIIString
end
"Foo" == "Foo"
true
X("Foo") == X("Foo")
false
but with Int instead of ASCIIString
immutable Y
y::Int
end
3 == 3
true
Y(3) == Y(3)
true
I had expected X("Foo") == X("Foo") to be true. Can anyone clarify why it is not?
Thank you.
Julia have two types of equality comparison:
If you want to check that x and y are identical, in the sense that no program could distinguish them. Then the right choice is to use is(x,y) function, and the equivalent operator to do this type of comparison is === operator. The tricky part is that two mutable objects is equal if their memory addresses are identical, but when you compare two immutable objects is returns true if contents are the same at the bit level.
2 === 2 #=> true, because numbers are immutable
"Foo" === "Foo" #=> false
== operator or it's equivalent isequal(x,y) function that is called generic comparison and returns true if, firstly suitable method for this type of argument exists, and secondly that method returns true. so what if that method isn't listed? then == call === operator.
Now for the above case, you have an immutable type that do not have == operator, so you really call === operator, and it checks if two objects are identical in contents at bit level, and they are not because they refer to different string objects and "Foo" !== "Foo"
Check source Base.operators.jl.
Read documentation
EDIT:
as #Andrew mentioned, refer to Julia documentation, Strings are of immutable data types, so why "test"!=="true" #=> true? If you look down into structure of a String data type e.g by xdump("test") #=> ASCIIString data: Array(UInt8,(4,)) UInt8[0x74,0x65,0x73,0x74], you find that Strings are of composite data types with an important data field. Julia Strings are mainly a sequence of bytes that stores in data field of String type. and isimmutable("test".data) #=> false

Specman: Why DAC macro interprets the type <some_name'exp> as 'string'?

I'm trying to write a DAC macro that gets as input the name of list of bits and its size, and the name of integer variable. Every element in the list should be constrained to be equal to every bit in the variable (both of the same length), i.e. (for list name list_of_bits and variable name foo and their length is 4) the macro's output should be:
keep list_of_bits[0] == foo[0:0];
keep list_of_bits[1] == foo[1:1];
keep list_of_bits[2] == foo[2:2];
keep list_of_bits[3] == foo[3:3];
My macro's code is:
define <keep_all_bits'exp> "keep_all_bits <list_size'exp> <num'name> <list_name'name>" as computed {
for i from 0 to (<list_size'exp> - 1) do {
result = appendf("%s keep %s[%d] == %s[%d:%d];",result, <list_name'name>, index, <num'name>, index, index);
};
};
The error I get:
*** Error: The type of '<list_size'exp>' is 'string', while expecting a
numeric type
...
for i from 0 to (<list_size'exp> - 1) do {
Why it interprets the <list_size'exp> as string?
Thank you for your help
All macro arguments in DAC macros are considered strings (except repetitions, which are considered lists of strings).
The point is that a macro treats its input purely syntactically, and it has no semantic information about the arguments. For example, in case of an expression (<exp>) the macro is unable to actually evaluate the expression and compute its value at compilation time, or even to figure out its type. This information is figured out at later compilation phases.
In your case, I would assume that the size is always a constant. So, first of all, you can use <num> instead of <exp> for that macro argument, and use as_a() to convert it to the actual number. The difference between <exp> and <num> is that <num> allows only constant numbers and not any expressions; but it's still treated as a string inside the macro.
Another important point: your macro itself should be a <struct_member> macro rather than an <exp> macro, because this construct itself is a struct member (namely, a constraint) and not an expression.
And one more thing: to ensure that the list size will be exactly as needed, add another constraint for the list size.
So, the improved macro can look like this:
define <keep_all_bits'struct_member> "keep_all_bits <list_size'num> <num'name> <list_name'name>" as computed {
result = appendf("keep %s.size() == %s;", <list_name'name>, <list_size'num>);
for i from 0 to (<list_size'num>.as_a(int) - 1) do {
result = appendf("%s keep %s[%d] == %s[%d:%d];",result, <list_name'name>, i, <num'name>, i, i);
};
};
Why not write is without macro?
keep for each in list_of_bits {
it == foo[index:index];
};
This should do the same, but look more readable and easier to debug; also the generation engine might take some advantage of more concise constraint.

Algorithm to evaluate value of Boolean expression

I had programming interview which consisted of 3 interviewers, 45 min each.
While first two interviewers gave me 2-3 short coding questions (i.e reverse linked list, implement rand(7) using rand(5) etc ) third interviewer used whole timeslot for single question:
You are given string representing correctly formed and parenthesized
boolean expression consisting of characters T, F, &, |, !, (, ) an
spaces. T stands for True, F for False, & for logical AND, | for
logical OR, ! for negate. & has greater priority than |. Any of these
chars is followed by a space in input string. I was to evaluate value
of expression and print it (output should be T or F). Example: Input:
! ( T | F & F ) Output: F
I tried to implement variation of Shunting Yard algorithm to solve the problem (to turn input in postfix form, and then to evaluate postfix expression), but failed to code it properly in given timeframe, so I ended up explaining in pseudocode and words what I wanted.
My recruiter said that first two interviewers gave me "HIRE", while third interviewer gave me "NO HIRE", and since the final decision is "logical AND", he thanked me for my time.
My questions:
Do you think that this question is appropriate to code on whiteboard in approx. 40 mins? To me it seems to much code for such a short timeslot and dimensions of whiteboard.
Is there shorter approach than to use Shunting yard algorithm for this problem?
Well, once you have some experience with parsers postfix algorithm is quite simple.
1. From left to right evaluate for each char:
if its operand, push on the stack.
if its operator, pop A, then pop B then push B operand A onto the stack. Last item on the stack will be the result. If there's none or more than one means you're doing it wrong (assuming the postfix notation is valid).
Infix to postfix is quite simple as well. That being said I don't think it's an appropriate task for 40 minutes if You don't know the algorithms. Here is a boolean postfix evaluation method I wrote at some stage (uses Lambda as well):
public static boolean evaluateBool(String s)
{
Stack<Object> stack = new Stack<>();
StringBuilder expression =new StringBuilder(s);
expression.chars().forEach(ch->
{
if(ch=='0') stack.push(false);
else if(ch=='1') stack.push(true);
else if(ch=='A'||ch=='R'||ch=='X')
{
boolean op1 = (boolean) stack.pop();
boolean op2 = (boolean) stack.pop();
switch(ch)
{
case 'A' : stack.push(op2&&op1); break;
case 'R' : stack.push(op2||op1); break;
case 'X' : stack.push(op2^op1); break;
}//endSwitch
}else
if(ch=='N')
{
boolean op1 = (boolean) stack.pop();
stack.push(!op1);
}//endIF
});
return (boolean) stack.pop();
}
In your case to make it working (with that snippet) you would first have to parse the expression and replace special characters like "!","|","^" etc with something plain like letters or just use integer char value in your if cases.