Unary operator '++' - swift

I am interested and beginning in Swift, but I can't fix that :
func countvalue(tableau : [String]){
var b : Int = 0
for var b in tableau {
b++ // Unary operator '++' cannot be applied to an operand of type #lvalue String'
}
print("Il y a \(b) valeurs dans ce tableau.")
}

The b in your loop is a different variable than the one outside the loop, and is masking it. Since tableau is an array of Strings, b in the loop is a String, and thus cannot be incremented.

I think what you want is this...
func countvalue(tableau : [String]){
var b : Int = 0
for _ in tableau {
// the values in the array are not used so just ignore them with _
b++ // Unary operator '++' cannot be applied to an operand of type #lvalue String'
}
print("Il y a \(b) valeurs dans ce tableau.")
}
But the value of b will be the same if you do...
var b = tableau.count
Except this is a lot more efficient as it does not have to iterate every value of the array.

Related

Custom Operator Precedence Issue in Swift?

I'm trying to implement a custom infix power operator using the "^" character with the following code, but I'm getting unexpected results.
precedencegroup PowerPrecedence {
associativity: right
lowerThan: BitwiseShiftPrecedence
higherThan: MultiplicationPrecedence
}
infix operator ^ : PowerPrecedence
func^(lhs:Float,rhs:Float) -> Float {
return pow(lhs,rhs)
}
When I use the ^ operator in the following statement,
let x = 1 + 10 ^ Float(2)
I expect x to be 1 + (10^2) = 101, but x is (1+10)^2 = 121 instead. What am I missing?

MiniZinc global_cardinality function with enums

According to the docs
A key behaviour of enumerated types is that they are automatically coerced to integers when they are used in a position expecting an integer. For example, this allows us to use global constraints defined on integers, such as global_cardinality_low_up
global_cardinality* family comes in two flavors: a predicate and a function. While in case of the predicates, arrays of enum items do indeed coerce to ints, with functions the coercion does not seem to work.
For example,
include "global_cardinality_closed.mzn";
enum MyEnum = {A, B, C};
array[1..2] of MyEnum: toCount = [A, C];
array[1..100] of var MyEnum: values;
%1
constraint let {
array[int] of var int: counts = global_cardinality_closed(values, toCount);
} in counts[1] > counts[2];
%2
constraint global_cardinality_closed(values, toCount, [5, 6]);
compiling the code snippet above in MiniZincIDE results in:
MiniZinc: type error: no function or predicate with this signature found: `global_cardinality_closed(array[int] of var MyEnum,array[int] of MyEnum)'
Cannot use the following functions or predicates with the same identifier:
predicate global_cardinality_closed(array[$_] of var int: x,array[$_] of int: cover,array[$_] of var int: counts);
(requires 3 arguments, but 2 given)
At the same time, the code after %2 compiles just fine.
Do I miss something or should I file a bug?
To make %1 work, you can either
include "global_cardinality_closed_fn.mzn";
or simply
include "globals.mzn";
The function is implemented by making use of the predicate:
include "global_cardinality_closed.mzn";
/** #group globals.counting
Returns an array with number of occurrences of \a cover[\p i] in \a x.
The elements of \a x must take their values from \a cover.
*/
function array[$Y] of var int: global_cardinality_closed(array[$X] of var int: x,
array[$Y] of int: cover) :: promise_total =
let { array[int] of int: cover1d = array1d(cover);
array[index_set(cover1d)] of var 0..length(x): counts;
constraint global_cardinality_closed(array1d(x),cover1d,counts); }
in arrayXd(cover,counts);

+= operator in Scala

I'm reading Programming in Scala by M. Odersky and now I'm trying to understand the meaning of operators. As far as I can see, any operator in Scala is just a method. Consider the following example:
class OperatorTest(var a : Int) {
def +(ot: OperatorTest): OperatorTest = {
val retVal = OperatorTest(0);
retVal.a = a + ot.a;
println("=")
return retVal;
}
}
object OperatorTest {
def apply(a: Int) = new OperatorTest(a);
}
I this case we have only + operator defined in this class. And if we type something like this:
var ot = OperatorTest(10);
var ot2 = OperatorTest(20);
ot += ot2;
println(ot.a);
then
=+
30
will be the output. So I'd assume that for each class (or type?) in Scala we have += operator defined for it, as a += b iff a = a + b. But since every operator is just a method, where the += operator defined? Maybe there is some class (like Object in Java) containing all the defenitions for such operators and so forth.
I looked at AnyRef in hoping to find, but couldn't.
+= and similar operators are desugared by the compiler in case there is a + defined and no += is defined. (Similarly works for other operators too.) Check the Scala Language Specification (6.12.4):
Assignment operators are treated specially in that they can be
expanded to assignments if no other interpretation is valid.
Let's consider an assignment operator such as += in an infix operation
l += r, where l, r are expressions. This operation can be
re-interpreted as an operation which corresponds to the assignment
l = l + r except that the operation's left-hand-side l is evaluated
only once.
The re-interpretation occurs if the following two conditions are
fulfilled.
The left-hand-side l does not have a member named +=, and also cannot
be converted by an implicit conversion to a value with a member named
+=. The assignment l = l + r is type-correct. In particular this implies that l refers to a variable or object that can be assigned to,
and that is convertible to a value with a member named +.

Optional argument in a method with ocaml

I encounter a problem with a optional argument in a method class.
let me explain. I have a pathfinding class graph (in the Wally module) and one his method shorthestPath. It use a optional argument. The fact is when I call (with or not the optional argument) this method OCaml return a conflict of type :
Error: This expression has type Wally.graph
but an expression was expected of type
< getCoor : string -> int * int;
getNearestNode : int * int -> string;
shorthestPath : src:string -> string -> string list; .. >
Types for method shorthestPath are incompatible
whereas shorthestPath type is :
method shorthestPath : ?src:string -> string -> string list
I same tried to use the option format for a optional argument :
method shorthestPath ?src dst =
let source = match src with
| None -> currentNode
| Some node -> node
in
...
Only in the case where I remove the optionnal argument, OCaml stop to insult me.
Thank you in advance for your help :)
It is not very clear what your situation is but I guess the following:
let f o = o#m 1 + 2
let o = object method m ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f o) (* type error. Types for method x are incompatible. *)
The use site (here the definition of f), the type of object is inferred from its context. Here, o : < x : int -> int; .. >. The method x's type is fixed here.
The object o defined later is independent from the argument of f and has the type < m : ?l:int -> int -> int; .. >. And unfortunately this type is incompatible with the other.
A workaround is to give more typing context to the use site about the optional argument:
let f o = o#m ?l:None 1 + 2 (* Explicitly telling there is l *)
let o = object method m ?l x = match l with Some y -> x + y | None -> x end
Or give the type of o:
class c = object
method m ?l x = ...
...
end
let f (o : #c) = o#m 1 + 2 (* Not (o : c) but (o : #c) to get the function more polymoprhic *)
let o = new c
let () = print_int (f o)
I think this is easier since there is usually a class declaration beforehand.
This kind of glitch between higher order use of functions with optional arguments happens also outside of objects. OCaml tries to resolve it nicely but it is not always possible. In this case:
let f g = g 1 + 2
let g ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f g)
is nicely typed. Nice!
The key rule: if OCaml cannot infer about omitted optional arguments, try giving some type context about them explicitly.

Type mismatch with If statement containing bitwise operators

I am new to scala but I am having the problem with the following code:
var c:Int = 0
var j:Int = 0
for( c <- 0 to 100){
for( j <- 0 to 100){
/* Check if jth bit in c is set,
if( (c & (1<<j)) ) // this line is the line where i get the error
xs :+ (ys(j)) // this is copying element j from list ys to list xs
}
}
The error I get is:
type mismatch; found : Int required: Boolean
the code (c & (1<<j)) should be shifting 1 left j bits and then bitwise anding the result to the int in the variable c to get a boolean result.
It is entirely possible that I am doing something wrong.. I have been learning Scala fro 3 days and I am very rusty on my java.
Any help would be appreicated
Bitwise operations in Scala (in fact in any language) return a result of type Int, your if expression requires a type of Boolean. Scala doesn't treat Boolean values like C, where you code would work fine.
You can make your expression return a Boolean by testing explicitly for 1:
if((c & (1 << j)) != 0)
Unlike in C (or C++), Scala's if statement (just like Java) only accepts a Boolean expression, and there is no implicit type promotion from integral types to Boolean. So you need to be explicit about what you want, and replace if( (c & (1<<j)) ) with if( (c & (1<<j)) != 0)