MiniZinc global_cardinality function with enums

Viewed 403

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?

1 Answers

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);
Related